title: R function with lapply
body: <p>I'm writing an R function using lapply to apply a lag difference transformation to a set of variables. The function computes the first difference of a number of different lags and lapply is used to iterate over a dataset containing many variables. Here is the code below.</p>
  
  <pre><code>## dt is my original dataset with 18 columns and 52 rows(observations)
  ## the dataframe df will contain the lagged differenced variables
  df&lt;-data.frame(index=c(1:nrow(dt)))
  
  for(i in 1:4){
    df[paste0(names(dt), '_lag',i,'_diff1')]&lt;-
         lapply(dt,function(x) diff      (x,lag=i,differences=1))  
   }
  </code></pre>
  
  <p>However, the above code throws an error as follows:</p>
  
  <blockquote>
    <p>Error in <code>[&lt;-.data.frame</code>(<code>*tmp*</code>, paste0(names(dt), "_lag",        i, "_diff1"),  : replacement element 1 has 51 rows, need 52</p>
  </blockquote>
  
  <p>I can't figure out where the error might be, because my dataset dt has 52 rows- not 51 as in the error message. Any help will be appreciated.</p>