title: Apply a shift function with different lead/lag offset to multiple columns in r
body: <p>I would like to apply the shift function in the data.table package to a data table containing 3 columns. This is what I have so far. </p>
  
  <pre><code>## Data table with 3 columns
  df &lt;- data.frame(X1 = c(0,0,1000,800,600,400,200), X2 = c(0,0,0,0,800,400,200), X3 = c(0,0,0,0,0,500,200))
  
  #X1  X2  X3
  #1    0   0   0
  #2    0   0   0
  #3 1000   0   0
  #4  800   0   0
  #5  600 800   0
  #6  400 400 500
  #7  200 200 200
  </code></pre>
  
  <p>First step is to locate the first non zero data (lead offset) in each column and store it in a dataframe to be used in "n" argument in the shift function. I used the following code;</p>
  
  <pre><code>num &lt;- as.numeric(apply(df, 2, function(x) head(which(x!=0),1)))
  </code></pre>
  
  <p>I appended the values from the above function to the last row of the dt table</p>
  
  <pre><code>df &lt;- rbind(df, num)
  </code></pre>
  
  <p>The goal is to run the shift function to all columns based on different leading offsets per column, as can be seen from the original table (i.e. nX1 = 3, nX2 = 5, nX3 = 6). I attempted this with the following code;</p>
  
  <pre><code>apply(df, 2, function(x, n) shift(x, n=n, fill=0, type="lead"), n = as.numeric(x[8, ]))
  </code></pre>
  
  <p>The above function applies all offset values to all columns instead of one lead offset per column. The desired table should look like this;</p>
  
  <pre><code>#  X1   X2  X3
  #1 1000 800 500
  #2 800  400 200
  #3 600  200 0
  #4 400  0   0
  #5 200  0   0
  #6 0    0   0
  #7 0    0   0
  </code></pre>
  
  <p>I appreciate any help I can get on fixing my code.
   Thank you.</p>