且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用另一列 R 替换一列中的值

更新时间:2022-03-14 21:55:19

可以使用mergeid进行匹配,然后在swl1列中替换code> 那些来自 datB 的项目存在:

You can use merge to match by id, then replace in column swl1 those items from datB which exist:

datC <- merge(datA, datB, all.x=TRUE)
datC
##   id swl1 swl2
## 1  1  0.8  0.8
## 2  2  0.7   NA
## 3  3  0.4  0.6
## 4  4  0.7   NA
## 5  5  0.0  0.7

这匹配行.现在将 swl1 列中的值替换为 swl2 列中的非 NA 值:

This matches up the rows. Now to replace those values in column swl1 with the non-NA values from column swl2:

datC$swl1 <- ifelse(is.na(datC$swl2), datC$swl1, datC$swl2)
datC$swl2 <- NULL
datC
##   id swl1
## 1  1  0.8
## 2  2  0.7
## 3  3  0.6
## 4  4  0.7
## 5  5  0.7