title: How to refer to previous row in data table (R) without using shift function?
body: <p>I am trying to use data table to make my massive modeling work easier. 
  I ran into this problem but have not figured out a better way to solve it. </p>
  
  <p>Here's my example:</p>
  
  <pre><code>set.seed(1001)
  dt1&lt;-data.table("Country"=c("Algeria","Mongolia"),
                  "Year"=c(2000:2020),
                  "var1"=runif(20,10000,45000),
                  "var2"=0,
                  "var3"=0,
                  "var4"=0)
  
  setorder(dt1,Country)  
  </code></pre>
  
  <p>I would like to update var2 by using previous row's values in a specific period
  so I tried</p>
  
  <pre><code>dt1[Year&gt;2000&amp;Year&lt;2010,var2:=var1[i]-sum(.SD)[i-1],by=Country,.SDcols=c(var2,var3,var4)]
  </code></pre>
  
  <p>Obviously this did not work. The problem is var 2 and the sum of other variables in previous row need to be updated simultaneously. So I don't think shift function would do the work.</p>
  
  <p>For now, I am using very cumbersome for loop for this but it works.Here is my forloop</p>
  
  <pre><code>for(i in 1:nrow(dt1)){
    if (i &lt;=10){
      for (j in 4:6){
        if(j==4){
          dt1[[i,j]]=dt1[[i,3]]-rowSums(dt1[[i-1,c(4:6)]])
        }
        else{
          dt1[[i,j]]=dt1[[i-1,j-1]] * 0.001
        }
      }
    }
  }
  </code></pre>
  
  <p>Any suggestion will be much appreciated!</p>