有条件地用 R 中的 NA 替换(两个数据帧)

Conditional Replacing with NA in R (two dataframes)

我有

    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)

它 returns 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 的行
  • jDT
  • 的连接子集中完成
  • jk := expr 时,更新 DT 的第 k