r - 在 R 中用 NA 有条件替换(两个数据帧)

标签 r replace conditional-statements na

我有

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

关于r - 在 R 中用 NA 有条件替换(两个数据帧),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142016/

相关文章:

r - 具有重复列名的堆栈

r - 查找两个线性拟合在R中相交的位置

python - (随机)替换字符串中 50% 的字符

ant - 在 ANT 中使用条件长度

java - 为什么无论输入是什么它都不会跳出循环

R_从 SpatialPolygonsDataFrame 中提取坐标

组内随机选择

regex - 如何用powershell替换每行的第一部分和最后一部分

javascript - VS 代码扩展 API - 替换文档中的字符串?

javascript - 比较二维数组与一维数组的值