title: Applying lags to data without loop
body: <p>Let's consider following data set:</p>
  <pre><code>library(plm)
  data(&quot;EmplUK&quot;, package = 'plm')
  df &lt;- EmplUK[1:6]
  head(df)
  &gt; head(df)
    firm year sector   emp    wage capital
  1    1 1977      7 5.041 13.1516  0.5894
  2    1 1978      7 5.600 12.3018  0.6318
  3    1 1979      7 5.015 12.8395  0.6771
  4    1 1980      7 4.715 13.8039  0.6171
  5    1 1981      7 4.093 14.2897  0.5076
  6    1 1982      7 3.166 14.8681  0.4229
  </code></pre>
  <p>As you can see it's basic panel data. Now I want to apply lag to this data set, but of course I don't want to apply lags to firm and year.</p>
  <p>Now let's define lag vector as <code>lags &lt;- c(2,1,3,0)</code>. It means that:</p>
  <p>(1) Two lags for sector (Third variable in data frame)</p>
  <p>(2) One lag for emp (Fourth variable in data frame)</p>
  <p>(3) Three lags for wage (Fifth variable in data frame)</p>
  <p>(4) Zero lags for capital (Sixth variable in data frame)</p>
  <p>Of course lags have to be applied with respect to convention of panel data - i.e. including lags at the beginning of each period.</p>
  <p><strong>My solution</strong></p>
  <pre><code>for (i in seq_len(length(lags))) {
    # Filter our data and apply lags for each time period
    df &lt;- df %&gt;%
      dplyr::group_by_at(1) %&gt;%
      # Take only those observations which amount 
      # is bigger than maximum number of lags
      dplyr::filter(n() &gt; max(lags)) %&gt;%
      dplyr::mutate(dplyr::across(
        colnames(df)[i + 2], dplyr::lag,
        n = lags[i], default = NA
      ))
  }
  
  &gt; head(df)
  
  &gt; head(df)
  # A tibble: 6 x 6
  # Groups:   firm [1]
     firm  year sector   emp  wage capital
    &lt;dbl&gt; &lt;dbl&gt;  &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;   &lt;dbl&gt;
  1     1  1977     NA NA     NA     0.589
  2     1  1978     NA  5.04  NA     0.632
  3     1  1979      7  5.60  NA     0.677
  4     1  1980      7  5.01  13.2   0.617
  5     1  1981      7  4.72  12.3   0.508
  6     1  1982      7  4.09  12.8   0.423 
  </code></pre>
  <p>However even though it's working I found it inconvenient - I did it using loop, but I'm certain that it's not necessary over there. Could you please give me a hand in rewriting code I did but without loop ?</p>