cbind a list of dataframes in R

Viewed 636

I have a list of 3 data.frames (X, Y, Z). Using BASE R, I was wondering how I could cbind similarly named variables across these data.frames and store them as a list?

For the example below, I want all variable AAs across the the 3 data.frames, all variable BBs across the the 3 data.frames, and all variable CCs the the 3 data.frames be separately cbinded and stored as a list?

Note: names could be anything, and the number of variables could be any number. A function(al) solution is highly appreciated.

r <- list( 

X = data.frame(

     AA = c(1,1,1,1,3,2), 
     BB = c(1,1,1,2,2,2), 
     CC = c(2,2,3,1,2,1)), 

Y = data.frame(

     AA = c(1,1,1,1,3,2), 
     BB = c(1,1,1,2,2,2), 
     CC = c(2,2,3,1,2,1)),

Z = data.frame(

     AA = c(1,1,1,1,3,2), 
     BB = c(1,1,1,2,2,2), 
     CC = c(2,2,3,1,2,1)))
2 Answers

A way using purrr and dplyr would be to tranpose the the list and then bind_cols together

library(dplyr)
library(purrr)

transpose(r) %>% map(bind_cols)

#$AA
# A tibble: 6 x 3
#      X     Y     Z
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     1     1     1
#3     1     1     1
#4     1     1     1
#5     3     3     3
#6     2     2     2

#$BB
# A tibble: 6 x 3
#      X     Y     Z
#    <dbl> <dbl> <dbl>
#1     1     1     1
#2     1     1     1
#3     1     1     1
#4     2     2     2
#....
#....

In base R, taking first dataframe of the list as reference dataframe, we can do

all_cols <- names(r[[1]])
#To get common names between all dataframes.
#all_cols <- Reduce(intersect, lapply(r, names)) 
lapply(all_cols, function(x) sapply(r, `[[`, x))

In base R, we can cbind the list elements to a single one and then do the split

m1 <- do.call(cbind, r)
split.default(m1, sub("^.*\\.", "", names(m1)))
Related