根据R中的其他数据框替换数据框中的值 [英] Replace values in data frame based on other data frame in R
本文介绍了根据R中的其他数据框替换数据框中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中, userids
是我的参考数据框,而 userdata
是我应该替换的数据框
In the below example, userids
is my reference data frame and userdata
is the data frame where the replacements should take place.
> userids <- data.frame(USER=c('Ann','Jim','Lee','Bob'),ID=c(1,2,3,4))
> userids
USER ID
1 Ann 1
2 Jim 2
3 Lee 3
4 Bob 4
> userdata <- data.frame(INFO=c('foo','bar','foo','bar'), ID=c('Bob','Jim','Ann','Lee'),AGE=c('43','33','53','26'), FRIENDID=c('Ann',NA,'Lee','Jim'))
> userdata
INFO ID AGE FRIENDID
1 foo Bob 43 Ann
2 bar Jim 33 NA
3 foo Ann 53 Lee
4 bar Lee 26 Jim
如何用对应的ID替换 userdata
中的ID和FRIENDID在 userids
中发送给USER?
How do I replace ID and FRIENDID in userdata
with the ID corresponding to USER in userids
?
所需的输出:
INFO ID AGE FRIENDID
1 foo 4 43 1
2 bar 2 33 NA
3 foo 1 53 3
4 bar 3 26 2
推荐答案
使用匹配
:
userdata$ID <- userids$ID[match(userdata$ID, userids$USER)]
userdata$FRIENDID <- userids$ID[match(userdata$FRIENDID, userids$USER)]
这篇关于根据R中的其他数据框替换数据框中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文