移位多列,每列具有不同的偏移量 [英] Shift multiple columns, each with a different offset
本文介绍了移位多列,每列具有不同的偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数据表:
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 0
我想将列a'向下'移位,每个列具有不同的偏移量。列 a完全不移。列 b应从第二行开始(下移1),列 c应下移2,依此类推。
I want to shift columns a-f 'down', each with a different offset. Column 'a' is not shifted at all. Column 'b' shall start in the second row (shifted down by 1), column 'c' shifted down 2, and so on.
当列下移时,上面的值应填充为0。data.table的行数不应增加:
When a column is shifted down, the values above should be filled with 0. The number of rows of the data.table should not increase:
date a b c d e f
2008 1 0 0 0 0 0
2008 3 5 0 0 0 0
2008 2 6 3 0 0 0
2009 5 8 2 6 0 0
2009 3 5 3 1 9 0
2010 2 3 3 4 5 8
推荐答案
您可以使用地图
将不同的 n
应用于每列:
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
这篇关于移位多列,每列具有不同的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文