【问题标题】:Combine multiple data frame with coincident columns将多个数据框与重合列合并
【发布时间】:2019-09-02 18:30:00
【问题描述】:

我想将多个 DataFrame 与一些重合的列组合成一个新的 DataFrame。新DataFrame的列应该是重合列。

例如,假设我有数据框 df1、df2、df3:

df1:
A   B   C   D
1   2   3   4

df2:
A   C   D   E
1   2  -1   5

df3:
C   D   F   G
0  -1   0   7

New dataframe
C   D 
3   4 
2  -1
0  -1

我曾尝试以循环方式使用匹配函数,以查找重合列:

match(df1,df2)

match(df2,df3)

match(df3,df1)

如果我有很多 DataFrame,这需要很多时间和线路。谁能提出一个更好的方法来做到这一点?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    一种选择是获取list 中的数据集并找到intersecting 列名称

    library(tidyverse)
    lst1 <- mget(paste0("df", 1:3))
    nm1 <- map(lst1, names) %>%
              reduce(intersect)    
    map_dfr(lst1, ~ .x %>% 
                      select(nm1))
    #  C  D
    #1 3  4
    #2 2 -1
    #3 0 -1
    

    或在base R

    nm1 <- Reduce(intersect, lapply(lst1, names))
    out <- do.call(rbind, lapply(lst1, subset, select = nm1))
    row.names(out) <- NULL
    

    数据

    df1 <- structure(list(A = 1L, B = 2L, C = 3L, D = 4L), class = "data.frame", row.names = c(NA, 
    -1L))
    
    df2 <- structure(list(A = 1L, C = 2L, D = -1L, E = 5L), class = "data.frame", row.names = c(NA, 
    -1L))
    
    df3 <- structure(list(C = 0L, D = -1L, F = 0L, G = 7L), class = "data.frame", row.names = c(NA, 
    -1L))
    

    【讨论】:

      猜你喜欢
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多