R:根据来自另一个数据帧的匹配条件添加行

时间:2021-06-08 22:18:49

标签: r dplyr

我有两个数据框,如下所示:

a<-c(1,1,-1,1,-1,1)
b<-c(0,200,0,0,0,45)
c<-c(4400,4403,4407,4408,4412,4423)
df1<-cbind(a,b,c)
df1<-as.data.frame(df1)
df1
   a   b    c
1  1   0 4400
2  1 200 4403
3 -1   0 4407
4  1   0 4408
5 -1   0 4412
6  1  45 4423

a<-c(1,1,-1,1,-1,1,-1,1,1,1,1)
b<-c(1,200,1,1,1,45,1,1,30,1,0)
c<-c(3400,3403,3407,3408,3412,3423,3436,3245,3234,3456,2345)
df2<-cbind(a,b,c)
df2<-as.data.frame(df2)
df2
    a   b    c
1   1   1 3400
2   1 200 3403
3  -1   1 3407
4   1   1 3408
5  -1   1 3412
6   1  45 3423
7  -1   1 3436
8   1   1 3245
9   1  30 3234
10  1   1 3456
11  1   1 2345

如何根据 b 列中的匹配列值向 df1 添加行? 因此,如果两个数据帧中 b 列中的值相同,则应将 df 2 中的相应行添加到 df1。

对于此示例,输出应如下所示

   a   b    c
1  1   0 4400
2  1 200 4403
3  1 200 3403
4 -1   0 4407
5  1   0 4408
6 -1   0 4412
7  1  45 4423
8  1  45 3423

dplyr 的所有连接函数都帮不了我。谢谢!

3 个答案:

答案 0 :(得分:5)

对于 b 列中的值,您可以索引到 df2 中:

rbind(df1, df2[(df2$b %in% df1$b),])

输出:

 a   b    c
 1   0 4400
 1 200 4403
-1   0 4407
 1   0 4408
-1   0 4412
 1  45 4423
 1 200 3403
 1  45 3423
 1   0 2345

答案 1 :(得分:5)

听起来好像您想要执行 semi_join 并将其绑定到您的 df1:


library(dplyr)

df1 %>% 
  bind_rows(semi_join(df2, df1, by = "b"))
#>    a   b    c
#> 1  1   0 4400
#> 2  1 200 4403
#> 3 -1   0 4407
#> 4  1   0 4408
#> 5 -1   0 4412
#> 6  1  45 4423
#> 7  1 200 3403
#> 8  1  45 3423
#> 9  1   0 2345

答案 2 :(得分:3)

我认为您可以使用以下解决方案:

library(dplyr)

df2 %>%
  filter(b %in% (df1$b %>%
           intersect(df2$b))) %>%
  bind_rows(df1) %>%
  arrange(b)

   a   b    c
1  1   0 4400
2 -1   0 4407
3  1   0 4408
4 -1   0 4412
5  1  45 3423
6  1  45 4423
7  1 200 3403
8  1 200 4403