Shift multiple columns, each with a different offset

前端 未结 3 751
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 10:04

    doing it manually with shift, which shifts a column (either leading or lagging for upward or downward) n units, padding with whatever you want:

    library(data.table)
    DT <- data.table(date=c(2008, 2008, 2008, 2009, 2009, 2010), a=c(1,3,2,5,3,2),b=c(5,6,8,5,3,8),c=c(3,2,3,3,2,3),d=c(6,1,4,6,2,7),e=c(9,5,3,9,5,7),f=c(8,8,0,8,5,0))
    
    DT[,b := shift(b, n=1, type="lag", fill=0)]
    DT[,c := shift(c, n=2, type="lag", fill=0)]
    DT[,d := shift(d, n=3, type="lag", fill=0)]
    DT[,e := shift(e, n=4, type="lag", fill=0)]
    DT[,f := shift(f, n=5, type="lag", fill=0)]
    

提交回复
热议问题