通过gre中的grepl合并两个数据帧

时间:2017-01-27 16:56:10

标签: r

假设我有两个数据框:

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

我想要的是在df2的df1中通过grepl df2的df2合并xx,以便达到预期的结果:

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

实际数据框架要大得多,似乎需要几行。我想知道是否有一种轻松的方式。

2 个答案:

答案 0 :(得分:6)

这是一个单行,在df2.x中搜索df1.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

答案 1 :(得分:1)

这是一个基本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”找不到匹配项。 [1]末尾的grep会强制使用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