为不同的行组创建唯一标识符

时间:2012-11-05 10:58:24

标签: r data.table sequences

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

tc <- textConnection('
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
')

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

目标是创建一个新列(“journey_nr”),根据其所属的旅程为每行提供唯一编号。旅程被定义为每id行至end_yn == 1的行序列,如果end_yn永远不会变为1,则旅程也应编号(请参阅预期的结果示例)。只能在ID的行集合末尾进行end_yn == 0次旅行(如第3行第3行所示)。因此,对于该ID或在end_yn == 1 - 旅程之前发生的事件没有end_yn == 0(请参阅示例中的id == abc)。

我知道如何使用data.table包进行编号,但我不知道要合并哪些列以获得预期结果。我在SO上搜索了data.table - 标签,但找不到类似的问题。

预期结果:

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

2 个答案:

答案 0 :(得分:4)

试试这个:

tc$journey <- cumsum(as.numeric(c(0, head(tc$end_yn, -1)) | c(0, diff(as.numeric(tc$id))))) + 1

tc
#    id time end_yn number journey
# 1 abc   10      0      1       1
# 2 abc   11      0      2       1
# 3 abc   12      1      3       1
# 4 abc   13      0      1       2
# 5 def   10      0      1       3
# 6 def   15      1      2       3
# 7 def   16      0      1       4
# 8 def   17      0      2       4
# 9 def   18      1      3       4

答案 1 :(得分:2)

另一个基地R回答:

test$journey <- cumsum(c(1,head(test$number,-1)) >= test$number)

结果:

> test
   id time end_yn number journey
1 abc   10      0      1       1
2 abc   11      0      2       1
3 abc   12      1      3       1
4 abc   13      0      1       2
5 def   10      0      1       3
6 def   15      1      2       3
7 def   16      0      1       4
8 def   17      0      2       4
9 def   18      1      3       4
相关问题