我想对数据帧中的某些行组合进行编号(按 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
条件?
我猜有不同的方法可以做到这一点,但这里有一种:
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
的密钥可能是值得的。