【问题标题】:Merge dataframes based on columns and rbind matches基于列和 rbind 匹配合并数据帧
【发布时间】:2020-02-14 15:14:21
【问题描述】:

我有两个数据框:

df <- data.frame(x=c("a","c"), y=c("111","222"))

df1 <- data.frame(x=c("a","b","b","c"), y=c("111","222","111","222"),z=c('xxx','yyy','ddd','ttt'))

我想基于 x 列合并这两个数据帧,这样,来自 df1 的匹配行应该作为行添加到 df,现在作为列添加,因为传统上合并函数在列上连接数据帧。生成的数据框应如下所示:

X  Y   Z
a 111 <NA>
a 111 xxx
c 222 <NA>
c 222 ttt

我知道它可以通过 for 循环来完成,但我想知道是否可以通过一/两行代码而不是编写多个 for 循环。

【问题讨论】:

    标签: r dataframe merge


    【解决方案1】:

    基础R 选项:

    # Add missing column to df
    df[setdiff(names(df1), names(df))] <- NA
    # rbind only rows matching on x
    rbind(df, df1[df1$x %in% df$x,])
       x   y    z
    1  a 111 <NA>
    2  c 222 <NA>
    11 a 111  xxx
    4  c 222  ttt
    

    dplyr 选项:

    library(dplyr)
    bind_rows(df, filter(df1, x %in% df$x))
      x   y    z
    1 a 111 <NA>
    2 c 222 <NA>
    3 a 111  xxx
    4 c 222  ttt
    

    data.table 选项:

    library(data.table)
    setDT(df)
    setDT(df1)
    rbind(df, df1[x %in% df$x], fill = TRUE)
       x   y    z
    1: a 111 <NA>
    2: c 222 <NA>
    3: a 111  xxx
    4: c 222  ttt
    

    【讨论】:

      【解决方案2】:
      library(dplyr)
      
      df1 %>%
          semi_join(df, by = "x") %>%
          bind_rows(df)
      
        x   y    z
      1 a 111  xxx
      2 c 222  ttt
      3 a 111 <NA>
      4 c 222 <NA>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 2021-01-29
        • 2020-10-15
        • 2015-08-10
        • 2013-12-01
        • 1970-01-01
        • 2020-10-10
        相关资源
        最近更新 更多