R中的条件合并/替换 [英] Conditional merge/replacement in R
本文介绍了R中的条件合并/替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数据框:
df1
x1 x2
1 a
2 b
3 c
4 d
和
df2
x1 x2
2 zz
3 qq
我想根据df1 $ x1和df2 $ x2之间的条件匹配,将df1 $ x2中的某些值替换为df2 $ x2中的值,以产生:
I want to replace some of the values in df1$x2 with values in df2$x2 based on the conditional match between df1$x1 and df2$x2 to produce:
df1
x1 x2
1 a
2 zz
3 qq
4 d
推荐答案
使用match()
,假设df1中的值是唯一的.
use match()
, assuming values in df1 are unique.
df1 <- data.frame(x1=1:4,x2=letters[1:4],stringsAsFactors=FALSE)
df2 <- data.frame(x1=2:3,x2=c("zz","qq"),stringsAsFactors=FALSE)
df1$x2[match(df2$x1,df1$x1)] <- df2$x2
> df1
x1 x2
1 1 a
2 2 zz
3 3 qq
4 4 d
如果值不是唯一的,请使用:
If the values aren't unique, use :
for(id in 1:nrow(df2)){
df1$x2[df1$x1 %in% df2$x1[id]] <- df2$x2[id]
}
这篇关于R中的条件合并/替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文