【问题标题】:How to subset a data frame based on a column of another data frame [duplicate]如何根据另一个数据框的列对数据框进行子集化[重复]
【发布时间】:2020-04-08 16:46:00
【问题描述】:

(已更新)我的 dataframe1 看起来像:

  A C D E F
1 c f x i e
2 d g i d d
3 e h p e e

和dataframe2:

  A B
1 c q
2 d m

请注意,dataframe2$A 是 dataframe1$A 的子集。如何根据 dataframe2 的 A 列对 dataframe1 进行子集化,并仅将 dataframe1 的 C 列添加到 dataframe2?我希望得到:

  A B C
1 c q f
2 d m g

【问题讨论】:

  • “基于dataframe2的A列的子集dataframe1”是什么意思?如果dataframe2$A 改为“c, z”,您是否只想要dataframe1 的c 行?还是dataframe2$Adataframe1$A 的子集总是正确的?
  • merge(df1, df2) 在基础 R 中,inner_join(df1, df2)dplyr 中。
  • merge(df1,df2,all.y=T) 甚至merge(df1,df2)
  • 嗨 @AaronMontgomery 是的,dataframe2$A 是 dataframe1$A 的子集

标签: r dataframe subset


【解决方案1】:

您可以使用来自 dplyr 的inner_join

library(dplyr)

df1 <- data.frame(A = c("c", "d", "e"),
           C = c("f", "g", "h"))

df2 <- data.frame(A = c("c", "d"),
                  B = c("q", "m"))

inner_join(df1, df2)
#> Joining, by = "A"
#> Warning: Column `A` joining factors with different levels, coercing to
#> character vector
#>   A C B
#> 1 c f q
#> 2 d g m

reprex package (v0.3.0) 于 2020 年 4 月 8 日创建

【讨论】:

  • 我用 inner_join 更新了答案
猜你喜欢
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 2020-12-01
  • 1970-01-01
相关资源
最近更新 更多