title: Group_by + lag repeat the same values for all groups in Shiny
body: <p>I'm making a Shiny app in which the user can generate a column in a table by clicking on a <code>checkboxInput</code>. The column I would like to create contains the lagged value of the column already present in the table.</p>
  
  <p>The code below shows a reproducible example: there are two individuals (<code>A</code> and <code>B</code>) and three time periods (<code>1</code>, <code>2</code> and <code>3</code>). </p>
  
  <pre><code>library(dplyr)
  library(shiny)
  
  data &lt;- head(mtcars)
  data$time &lt;- rep(seq(1:3))
  data$ID &lt;- rep(c("A", "B"), each = 3)
  
  ui &lt;- fluidPage(
    selectInput("choice", "Select a column", choices = c("mpg", "drat", "hp"), multiple = F),
    checkboxInput("lag", "Compute lag value"),
    tableOutput("table")
  )
  
  server &lt;- function(input, output, session) {
  
    data2 &lt;- reactive({
      lagged_name &lt;- paste0(input$choice, "_lagged")
      if (input$lag){
        data %&gt;%
          select(ID, time, input$choice) %&gt;%
          group_by(ID) %&gt;%
          mutate(!!all_of(lagged_name) := lag(data[, input$choice]))
      }
      else {
        data %&gt;%
          select(ID, time, input$choice)
      }
    })
  
    output$table &lt;- renderTable({
      data2()
    })
  }
  
  shinyApp(ui, server)
  </code></pre>
  
  <p>When I run this code and click on the checkbox, I have the error:</p>
  
  <blockquote>
    <p>Warning: Error in : Column <code>mpg_lagged</code> must be length 3 (the group size) or one, not 6</p>
  </blockquote>
  
  <p>Thanks to <a href="https://stackoverflow.com/questions/28235074/dplyr-lead-and-lag-wrong-when-used-with-group-by">this answer</a>, I corrected it by adding <code>order_by = ID</code> in the <code>lag</code> function but now there is another problem: for individual <code>1</code>, it creates the right lagged values, but then those values are repeated for individual <code>2</code> as well whereas they do not correspond.</p>
  
  <p>I tried a similar example without the Shiny environment and the right output is produced so I suppose this problem comes from the inputs or reactive environment. </p>
  
  <p>Does anybody have a solution?</p>