2017-06-19 41 views
0

我试图通过比较列x的值与不同数据框(df2)中列y的值在现有数据框(df1)中创建一个新列。基于两列之间的匹配的数据帧中的新列

结果应该看起来像df_end。如果有匹配,则应返回第x列的值。如果没有匹配,则应退还NA。

df1 <- data.frame(x = c("blue2", "blue6", "green9", "green7")) 
df2 <- data.frame(y = c("blue2", "green9")) 

df_end <- data.frame(x = c("blue2", "blue6", "green9", "green7"), 
        match = c("blue2", NA, "green9", NA)) 

我已经试验过merge,match和if,else语句,但我无法弄清楚。有人对我有一个建议吗?

#Attempt 1: Merge 
df1$match <- merge(df1, df2, by.x = x, all = TRUE) 

这不起作用,因为df1和df2长度不同。

+0

使用'和调整' by.x'和'by.y'参数来匹配各自的变量名称。 – lmo

+2

'df2 $ y [match(df1 $ x,df2 $ y)]' – Sotos

回答

1

我做了以下内容:

df1 <- data.frame(x = c("blue2", "blue6", "green9", "green7")) 
df2 <- data.frame(y = c("blue2", "green9")) 

end <- sapply(df1$x, function(x) { # for each value in df1$x 
    j <- which(df2$y == x) # check if df2$y has a match 
    ifelse(length(j) > 0, j, NA) # if there is, give the location in the vector 
}) # if not give NA 

cbind(df1,df2, match = df2$y[end]) # subset the df2 with the location to get the characters 

#  x  y match 
#1 blue2 blue2 blue2 
#2 blue6 green9 <NA> 
#3 green9 blue2 green9 
#4 green7 green9 <NA> 

编辑: 看到索托斯的最佳答案评论:merge`与`所有= TRUE`参数df2$y[match(df1$x, df2$y)]

+0

此解决方案有效。最终我用了sotos解决方案,因为它更简洁一些:) – SHW

+0

是的,我不知道为什么我在匹配函数XD上空白 –

相关问题