如何基于* partial *行重叠合并数据帧?

问题描述 投票:1回答:2

我想合并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对此不太合适。什么是?

r dataframe merge
2个回答
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

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

Data

#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")
© www.soinside.com 2019 - 2024. All rights reserved.