按变量对行进行编号,但在条件被触发时重新开始

时间:2012-10-19 07:57:46

标签: r data.table sequences

我想对数据帧中的某些行组合进行编号(按ID和时间排序)

tc <- textConnection('
id              time       end_yn
abc             10         0
abc             11         0
abc             12         1
abc             13         0
def             10         0
def             15         1
def             16         0
def             17         0
def             18         1
')

test <- read.table(tc, header=TRUE)

目标是创建一个新列(“number”),该列从id开始每1 to n对每行进行编号,直至end_yn == 1被点击。在end_yn == 1之后,编号应该重新开始。

如果不考虑end_yn == 1条件,可以使用以下代码对行进行编号:

DT <- data.table(test)
DT[, id := seq_len(.N), by = id]

然而,预期的结果应该是:

id              time       end_yn   number
abc             10         0        1
abc             11         0        2
abc             12         1        3 
abc             13         0        1 
def             10         0        1
def             15         1        2
def             16         0        1
def             17         0        2
def             18         1        3

如何纳入end_yn == 1条件?

1 个答案:

答案 0 :(得分:5)

我猜有不同的方法可以做到这一点,但这里有一个:

DT[, cEnd := c(0,cumsum(end_yn)[-.N])] # carry the end value forward

DT[, number := seq_len(.N), by = "id,cEnd"] # create your sequence

DT[, cEnd := NULL] # remove the column created above

id设为DT的关键可能值得。