简体   繁体   English

R合并2个具有相似变量的数据帧

[英]R Merge 2 data.frames with similar variables

Is it possible to merge two data.frame without having exactly the same variables in the two df. 是否可以合并两个data.frame而在两个df中没有完全相同的变量。

Example: 例:

df1 <-  data.frame(C=c("1Q","4R"),B= c("A","plane"))
df <-  data.frame(A=c(1,2),B=c("A (Inc", "plane (Inc)"))

> df
#  A           B
#1 1      A (Inc
#2 2 plane (Inc)

> df1
#   C     B
#1 1Q     A
#2 4R plane

Is it possible to merge df1 and df? 可以合并df1和df吗? Here I don't want to pre-modify the data in the dfs for the match to occur. 在这里,我不想预先修改dfs中的数据以使匹配发生。 I'm would like the merge to discard the (Inc), while keeping it in the dfs. 我希望合并丢弃(Inc),同时将其保留在dfs中。 An obvious soluion in this dumb example would be cbind() , but it's really the merge that I'm looking for. 在这个愚蠢的示例中,一个明显的解决方案是cbind() ,但这实际上是我正在寻找的合并。

My merged data.frame would be: 我合并的data.frame将是:

df

#    C     B A           B
# 1 1Q     A 1      A (Inc
# 2 4R plane 2 plane (Inc)

You can proceed like this: 您可以这样进行:

> merge(df1,transform(df, B = gsub("[[:space:]]*\\(Inc.*$","",df$B), B1=df$B))
      B  C A          B1
1     A 1Q 1      A (Inc
2 plane 4R 2 plane (Inc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM