如何基于*部分*行重叠来合并数据帧?

时间:2019-04-30 21:35:37

标签: r dataframe merge

我想在R中合并数据帧,以便仅保留那些行在数据帧中部分对应的观测值。

我有两个数据框(这些是玩具数据框-实际的有数百列。)

    V1             V2      V3 
    rabbit         001     M
    squirrel       001     M
    cow            001     M
    rabbit         004     M
    squirrel       004     M
    skunk          004     M

    V1             V2       V3
    rabbit         001      B
    squirrel       001      B
    skunk          001      B
    rabbit         004      B
    squirrel       004      B
    skunk          008      B

所需结果:

    V1             V2       V3
    rabbit         001      M
    squirrel       001      M
    rabbit         004      M
    squirrel       004      M
    rabbit         001      B
    squirrel       001      B
    rabbit         004      B
    squirrel       004      B

merge和dplyr :: inter_join并不是正确的功能。什么?

2 个答案:

答案 0 :(得分:2)

rbind(d1, d2)[ave(1:(nrow(d1) + nrow(d2)),
           Reduce(paste, rbind(d1, d2)[c("V1", "V2")]),
           FUN = length) > 1,]
#         V1 V2 V3
#1    rabbit  1  M
#2  squirrel  1  M
#4    rabbit  4  M
#5  squirrel  4  M
#7    rabbit  1  B
#8  squirrel  1  B
#10   rabbit  4  B
#11 squirrel  4  B

数据

#dput(d1)
structure(list(V1 = c("rabbit", "squirrel", "cow", "rabbit", 
"squirrel", "skunk"), V2 = c(1L, 1L, 1L, 4L, 4L, 4L), V3 = c("M", 
"M", "M", "M", "M", "M")), row.names = c(NA, 6L), class = "data.frame")

#dput(d2)
structure(list(V1 = c("rabbit", "squirrel", "skunk", "rabbit", 
"squirrel", "skunk"), V2 = c(1L, 1L, 1L, 4L, 4L, 8L), V3 = c("B", 
"B", "B", "B", "B", "B")), row.names = 7:12, class = "data.frame")

答案 1 :(得分:1)

d.b's answer可能会更有效率,但是如果您希望从JOIN操作的角度考虑问题,则可以使用3个dplyr连接操作来实现:

library(dplyr)

# Perform an inner_join with just the columns that you want to match
match_rows <- inner_join(df1[,1:2], df2[,1:2])
match_rows

        V1 V2
1   rabbit  1
2 squirrel  1
3   rabbit  4
4 squirrel  4

# Then left_join that with each dataframe to get the matching rows from each
#  and then bind them together as rows
bind_rows(left_join(match_rows, df1),
          left_join(match_rows, df2))

        V1 V2 V3
1   rabbit  1  M
2 squirrel  1  M
3   rabbit  4  M
4 squirrel  4  M
5   rabbit  1  B
6 squirrel  1  B
7   rabbit  4  B
8 squirrel  4  B