Shift multiple columns, each with a different offset

前端 未结 3 749
Happy的楠姐
Happy的楠姐 2021-01-01 09:25

I have a data.table like this:

 date a b c d e f 
 2008 1 5 3 6 9 8 
 2008 3 6 2 1 5 8
 2008 2 8 3 4 3 0
 2009 5 5 3 6 9 8
 2009 3 3 2 2 5 5
 2010 2 8 3 7 7          


        
3条回答
  •  春和景丽
    2021-01-01 09:48

    You can use Map to apply a different n to each column:

    cols <- setdiff(names(DT), "date")
    DT[, (cols) := Map(shift, .SD, seq_along(.SD) - 1L, fill = 0), .SDcols = cols]
    
    > DT
       date a b c d e f
    1: 2008 1 0 0 0 0 0
    2: 2008 3 5 0 0 0 0
    3: 2008 2 6 3 0 0 0
    4: 2009 5 8 2 6 0 0
    5: 2009 3 5 3 1 9 0
    6: 2010 2 3 3 4 5 8
    

提交回复
热议问题