如何合并具有不同大小的匹配列值的数据框列表

时间:2018-06-28 16:19:16

标签: r

我发现一些问题已经回答,但在这里找不到我真正需要的。我有一个名为test的数据框列表,具有不同的列名,但是它们具有匹配的键列。我想基于key值合并所有数据框,并获得以下结果:

test<- list(structure(list(key = structure(c(2L, 3L, 1L), .Label = c("Datsun 710", 
"Mazda RX4", "Mazda RX4 Wag"), class = "factor"), mpg1 = c(23, 
22, 2.8), cyl1 = structure(c(2L, 2L, 1L), .Label = c("4", "6", 
"8"), class = "factor")), .Names = c("key", "mpg1", "cyl1"), row.names = c(NA, 
3L), class = "data.frame"), structure(list(key = structure(2L, .Label = c("Datsun 710", 
"Mazda RX4", "Mazda RX4 Wag"), class = "factor"), mpg2 = 21, 
    cyl2 = structure(2L, .Label = c("4", "6", "8"), class = "factor")), .Names = c("key", 
"mpg2", "cyl2"), row.names = 1L, class = "data.frame"), structure(list(
    key = structure(c(3L, 1L), .Label = c("Datsun 710", "Mazda RX4", 
    "Mazda RX4 Wag"), class = "factor"), mpg3 = c(42, 32.8), 
    cyl3 = structure(c(2L, 1L), .Label = c("4", "6", "8"), class = "factor")), .Names = c("key", 
"mpg3", "cyl3"), row.names = 2:3, class = "data.frame"))

我想要的结果:

key              mpg1      cyl1     mpg2    cyl2    mpg3    cyl3
Mazda RX4       23          6        21       6     
Mazda RX4 Wag   22          6                         42      6
Datsun 710      2.8         4                         32.8    4

1 个答案:

答案 0 :(得分:2)

我们可以将reducefull_join一起使用

library(tidyverse)
test %>% 
      reduce(full_join, by = 'key')
#            key mpg1 cyl1 mpg2 cyl2 mpg3 cyl3
#1     Mazda RX4 23.0    6   21    6   NA <NA>
#2 Mazda RX4 Wag 22.0    6   NA <NA> 42.0    6
#3    Datsun 710  2.8    4   NA <NA> 32.8    4

或与base R

Reduce(function(...) merge(..., all = TRUE, by = "key"), test)