How to loop lapply to create LAG terms over multiple variables in R

后端 未结 2 1362
温柔的废话
温柔的废话 2021-01-03 15:32

For a model I\'m building, I want to create multiple lag terms for every field/vector in my data table:

For example, with the following data table:



        
2条回答
  •  迷失自我
    2021-01-03 16:09

    data.table and Map to handle the looping:

    vars <- c("b","c")
    rpv  <- rep(1:2, each=length(vars))
    df[, paste(vars, "lag", rpv, sep="_") := Map(shift, .SD, rpv), by=a, .SDcols=vars]
    
    #   a         b        c   b_lag_1  c_lag_1  b_lag_2  c_lag_2
    #1: x 10.863180 393.9568        NA       NA       NA       NA
    #2: x  6.139258 537.9199 10.863180 393.9568       NA       NA
    #3: x 11.896448 483.8036  6.139258 537.9199 10.86318 393.9568
    #4: y 18.079188 509.6136        NA       NA       NA       NA
    #5: y  5.463224 233.6991 18.079188 509.6136       NA       NA
    #6: y  6.363724 869.8406  5.463224 233.6991 18.07919 509.6136
    

提交回复
热议问题