按组增加价值

时间:2017-01-23 17:06:55

标签: r data.table

如果组内发生变化,如何增加列?

示例data.table:

library(data.table)
dt = data.table(id = c(1,1,1,1,2,2), loc = c(1,1,1,2,1,1), var = c("N","Y","N","N","N","N"))

   id loc var
1:  1   1   N
2:  1   1   Y
3:  1   1   N
4:  1   2   N
5:  2   1   N
6:  2   1   N

我想按id和loc进行分组,每当列var更改时,我想将1添加到新列。

期望的输出:

   id loc var V2
1:  1   1   N  1
2:  1   1   Y  2
3:  1   1   N  3
4:  1   2   N  1
5:  2   1   N  1
6:  2   1   N  1

1 个答案:

答案 0 :(得分:1)

dt[ , rleid(var),by = .(id, loc)]
#   id loc V1
#1:  1   1  1
#2:  1   1  2
#3:  1   1  3
#4:  1   2  1
#5:  2   1  1
#6:  2   1  1