我有
idx <- c(1397, 2000, 3409, 3415, 4077, 4445, 5021, 5155)
idy <- c( 1397, 2000, 2860, 3029, 3415, 3707, 4077, 4445, 5021, 5155,
5251, 5560)
agex <- c(NA, NA, NA, 35, NA, 62, 35, 46)
agey <- c( 3, 45, 0, 89, 7, 2, 13, 24, 58, 8, 3, 45)
dat1 <- as.data.frame(cbind(idx, agex))
dat2 <- as.data.frame(cbind(idy, agey))
现在我想要每当agex = NA并且idx = idy时,agey = NA,这样
idy agey
1 1397 NA
2 2000 NA
3 2860 0
4 3029 89
5 3415 7
6 3707 2
7 4077 NA
8 4445 24
9 5021 58
10 5155 8
11 5251 3
12 5560 45
我已经尝试过了
ifelse(is.na(dat1$agex) | dat1$idx %in% dat2$idy, NA, dat2$agey)
它返回正确索引处的 NA,但将 idy 缩短为 idx 的长度。
最佳答案
I want whenever agex = NA, and idx = idy, that agey = NA
通过 data.table 更新连接...
library(data.table)
setDT(dat1); setDT(dat2)
dat2[dat1[is.na(agex)], on=.(idy = idx), agey := NA]
dat2
idy agey
1: 1397 NA
2: 2000 NA
3: 2860 0
4: 3029 89
5: 3415 7
6: 3707 2
7: 4077 NA
8: 4445 24
9: 5021 58
10: 5155 8
11: 5251 3
12: 5560 45
工作原理
dat1[is.na(agex)]
是agex
为 NA 的子集DT[mDT, on=, j]
是一个联接,其中使用on 在
DT
中查找mDT
行=j
在DT
的连接子集中完成- 当
j
为k := expr
时,更新DT
的k
列
关于r - 在 R 中用 NA 有条件替换(两个数据帧),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142016/