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

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

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 的所有连接函数都帮不了我。谢谢!

回答

您可以索引df2b 列中的值:

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


回答

听起来好像你想要做一个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

  • @AnoushiravanR I think this is because there is a small error in the OP's original example - the code to produce `df2` has a 0 as the last value in col 'b' but the printed data frame has a 1.

以上是R:根据来自另一个数据帧的匹配条件添加行的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>