用另一列 R 替换一列中的值 [英] replacing values in a column with another column R

查看:42
本文介绍了用另一列 R 替换一列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同维度的表,现在我想根据用户 ID 用 datB$swl2 中的值替换值 datA$swl1.

I have two tables in different dimensions, now I want to replace value datA$swl1 with values in datB$swl2 according to userids.

数据

 id swl1
 1   0.8
 2   0.7
 3   0.4
 4   0.7
 5   0.0

数据B

id   swl2
 1   0.8
 3   0.6
 5   0.7

输出

datA(这里swl1被swl2中的新值代替,但并不是所有的id都有新值,没有的,保留原值)

datA (here swl1 is replaced by the new values in swl2, but not all the ids have a new values, for those that haven't, the original values are retained)

 id swl1
 1   0.8
 2   0.7
 3   0.6
 4   0.7
 5   0.7

如何做到这一点?

推荐答案

可以使用mergeid进行匹配,然后在swl1 那些来自 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

这篇关于用另一列 R 替换一列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆