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

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

问题描述

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

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

datA

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

datB

id   swl2
 1   0.8
 3   0.6
 5   0.7

输出

datA(此处swl1被swl2中的新值代替,但并非所有id都有新值,对于没有的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

该怎么做?

推荐答案

您可以使用merge匹配id,然后在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天全站免登陆