Reputation: 5719
I found some questions already answered, but couldn't find exactly what I need here. I have a list of dataframes called test
with different column names, but they have matching key column. I want to merge all dataframes based on key
values and get the result below:
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"))
result I want:
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
Upvotes: 1
Views: 34
Reputation: 886938
We can use reduce
with full_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
Or with base R
Reduce(function(...) merge(..., all = TRUE, by = "key"), test)
Upvotes: 2