我有这些数据:
ID <- c(7,7,7,3,3,4,4,4,10,10,5)
t <- c(NA,NA,NA,1,NA,NA,NA,NA,2,NA,3)
z <- c(NA,NA,NA,7,NA,NA,NA,NA,4,NA,10)
dt <- data.table(ID,t,z)
ID t z
1: 7 NA NA
2: 7 NA NA
3: 7 NA NA
4: 3 1 7
5: 3 NA NA
6: 4 NA NA
7: 4 NA NA
8: 4 NA NA
9: 10 2 4
10: 10 NA NA
11: 5 3 10
我希望按此顺序发生:
每当ID出现7时,当t = 1时它会更改为ID值
每当ID出现4时,当t = 2
每当ID出现10时,当t = 3时它会更改为ID值
我试过这个,但它不起作用,我需要重复这个t = 1,t = 2和t = 3:
dt[ID[match(ID, z[t == 1L])], ID := ID[t == 1L]]
dt[ID[match(ID, z[t == 2L])], ID := ID[t == 2L]]
dt[ID[match(ID, z[t == 3L])], ID := ID[t == 3L]]
是否可以更正我的代码,然后找到一种更简单的方法从t = 1到t = 3按顺序重复它?
所需的结果如下所示,因为在ID中,4s已更改为10s,然后10s已更改为5s:
ID t z
1: 3 NA NA
2: 3 NA NA
3: 3 NA NA
4: 3 1 7
5: 3 NA NA
6: 5 NA NA
7: 5 NA NA
8: 5 NA NA
9: 5 2 4
10: 5 NA NA
11: 5 3 10
非常感谢
答案 0 :(得分:1)
我们可以通过删除NA行
创建数据集后使用for
循环执行此操作
dt1 <- dt[complete.cases(t,z)]
#Or
#dt1 <- na.omit(dt)
#loop through the sequence of rows in 'dt1'
#based on the logical index on 'i' for 'ID', assign 'ID' to the corresponding 'ID' in 'dt1'
for(i in seq_len(nrow(dt1))){
dt[ID %in% dt1$z[i], ID := dt1$ID[i]][]
}
dt
# ID t z
# 1: 3 NA NA
# 2: 3 NA NA
# 3: 3 NA NA
# 4: 3 1 7
# 5: 3 NA NA
# 6: 5 NA NA
# 7: 5 NA NA
# 8: 5 NA NA
# 9: 5 2 4
#10: 5 NA NA
#11: 5 3 10
答案 1 :(得分:0)
只要ID中出现7,当t = 1时,它就会变为ID值
ID[which(ID==7)]=ID[which(t==1)]
只要ID出现4,当t = 2
时,它就会变为ID值ID[which(ID==4)]=ID[which(t==2)]
每当ID出现10时,当t = 3时,它就会变为ID值
ID[which(ID==10)]=ID[which(t==3)]