我想使用上一组行中的值,类似于data.table::shift
,但值按组移动。目前,我这样做(我要创建的变量是prev_block
):
dt<-data.table(expand.grid(group=c('a','b'),id=1:4, block=1:3, repn=1:3))
setorder(dt,group, id, block, repn)
dt[,prev_block:=shift(block), by=.(group, id)]
dt[1:5]
group id block repn prev_block
1: a 1 1 1 NA
2: a 1 1 2 1
3: a 1 1 3 1
4: a 1 2 1 1
5: a 1 2 2 2
dt[,prev_block:=prev_block[1], by=.(group, id, block)]
dt[3:8]
group id block repn prev_block
1: a 1 1 1 NA
2: a 1 1 2 NA
3: a 1 1 3 NA
4: a 1 2 1 1
5: a 1 2 2 1
有可能用一条线做吗?
我试图为它制作一个功能,但因为无法修改而陷入困境.SD:
shift2<-function(.SD, x, ...){
.SD[,tmp_var:=shift(get(x))]
.SD[,tmp_var:=tmp_var[1],by=...]
.SD[,tmp_var]
}