我有一个如下所示的数据集:
id age mod
1 1 1
1 5 0
1 6 1
1 7 1
1 9 1
2 3 0
2 4 1我想先创建一个变量,并且只在第一次出现mod时(每一集从mod==1开始)才给它赋值true。一集可以定义为年龄递增1或年龄递增2的mod==1的系列(或独立日)。换句话说,如果age== 2和mod==1,age==3和mod==0以及age==4和mod==1,2-4岁仍然是同一系列的一部分,因为它们仍然在2天内。
因此,理想情况下,最终数据集应如下所示:
id age mod first
1 1 1 TRUE
1 5 0 FALSE
1 6 1 TRUE
1 7 1 FALSE
1 9 1 FALSE
2 3 0 FALSE
2 4 1 TRUE我曾尝试在data.table中使用LAG语句,但没有成功。
发布于 2019-12-31 01:59:04
简单的条件是mod[i]==1 & mod[i-1]==0。也就是说,如果一行的mod值为1,而前一行的mod值为0,则将其标记为first。
这应该是可行的:
d = read.table(text='id age mod
1 1 1
1 5 0
1 6 1
1 7 1
1 9 1
2 3 0
2 4 1', header=T)
d$first[1] = (d$mod[1]==1)
d$first[2:nrow(d)] = (d$mod[2:nrow(d)]==1 & d$mod[1:nrow(d)-1]==0)发布于 2019-12-31 06:45:21
我相信这应该符合你的标准。这可能可以在一个冗长、复杂的一行代码中完成,但我认为为了清晰起见,将其分成多个步骤将达到相同的目的,而不会对性能造成有意义的影响。
library(data.table)
## Note - I added a couple more sample rows here
DT <- fread("id age mod
1 1 1
1 5 0
1 6 1
1 7 1
1 9 1
2 3 0
2 4 1
3 1 1
3 5 0
3 9 1
3 10 1")
## Create a column to track jumps in age
DT[, agejump := age - shift(age, n = 1L, fill = NA, type = "lag") > 2L, by = .(id)]
## Create a column to define continued sequences
DT[, continued := mod == 1 & shift(mod, n = 1L, fill = NA, type = "lag") == 1L, by = .(id)]
## backfill the first row of NA's for each id for both variables with FALSE
DT[DT[, .I[1], by = .(id)]$V1, c("agejump","continued") := FALSE]
## define first
DT[,first := (mod == 1 & continued == FALSE | mod == 1 & continued == TRUE & agejump == TRUE)]
print(DT)
# id age mod agejump continued first
# 1: 1 1 1 FALSE FALSE TRUE
# 2: 1 5 0 TRUE FALSE FALSE
# 3: 1 6 1 FALSE FALSE TRUE
# 4: 1 7 1 FALSE TRUE FALSE
# 5: 1 9 1 FALSE TRUE FALSE
# 6: 2 3 0 FALSE FALSE FALSE
# 7: 2 4 1 FALSE FALSE TRUE
# 8: 3 1 1 FALSE FALSE TRUE
# 9: 3 5 0 TRUE FALSE FALSE
# 10: 3 9 1 TRUE FALSE TRUE
# 11: 3 10 1 FALSE TRUE FALSEhttps://stackoverflow.com/questions/59534802
复制相似问题