2017-01-27 80 views
0

假设我有两个数据帧,使得:R中由grepl合并两个数据帧

df1<-data.frame(x=c("abc", "def", "ghi", NA), y=1:4) 
df1 
    x y 
1 abc 1 
2 def 2 
3 ghi 3 
4 NA 4 
df2<-data.frame(x=c("a", "i"), z=4:5) 
df2 
    x z 
1 a 4 
2 i 5 

我想什么是grepl DF2的x在合并df1df2 DF2的x使得期望的结果将是:

df3 
    x y z 
1 abc 1 4 
2 def 2 NA 
3 ghi 3 5 
4 NA 4 NA 

实际的数据帧更大,似乎需要几行。我想知道是否可能有一个简单的方法。

回答

5

这里是留下一个一行上在df1.xdf2.x搜索联接:

library(sqldf) 

sqldf("select df1.*, df2.z from df1 left join df2 on instr(df1.x, df2.x)") 

给予:

 x y z 
1 abc 1 4 
2 def 2 NA 
3 ghi 3 5 
4 <NA> 4 NA 
0

这里是一个基R法如果的每一个元素,将工作df2与df1的元素具有单个匹配:

# initialize new varible with NAs 
df1$z <- NA 
# fill in matching indices with df2$z 
df1$z[sapply(df2$x, function(i) grep(i, df1$x, fixed=TRUE))] <- df2$z 

sapply(df2$x, function(i) grep(i, df1$x, fixed=TRUE))将贯穿df2$x的每个元素并找到df1$x内的匹配位置,输出将是一个向量。


为了使这个强大的非比赛两者之间,你可以做到以下几点。在下面的例子中,“j”找不到匹配项。 grep末尾的[1]强制为NA,而不是默认值integer(0)

# get indices match with NAs for non-matches 
matches <- unlist(lapply(c("a", "j"), function(i) grep(i, df1$x, fixed=TRUE)[1])) 
matches 
[1] 1 NA 

现在,将此与is.na一起用于子集化子载体的子集。

df1$z[matches[!is.na(matches)]] <- df2$z[!is.na(matches)] 
df1 
    x y z 
1 abc 1 4 
2 def 2 NA 
3 ghi 3 NA 
4 <NA> 4 NA