Dot Dumuid
Dot Dumuid

Reputation: 69

how to create a new list of data.frames by systematically rearranging columns from an existing list of data.frames

I have a list of about 100 data frames. I would like to create a new list of data frames where the first data frame is made up of the first columns of all the existing data frames, and the second data frame is made up of the second column etc...

Please see code below for an example of what I want to do.

a <- c(0, 0, 1, 1, 1)
b <- c(0, 1, 0, 0, 1)
c <- c(1, 1, 0, 0, 1)
df1 <- data.frame(a, b, c)
df2 <- data.frame(c, b, a)
df3 <- data.frame(b, a, c)
my_lst <- list(df1, df2, df3)

new_df1 <- data.frame(df1[,1], df2[,1], df3[,1])
new_df2 <- data.frame(df1[,2], df2[,2], df3[,2])
new_df3 <- data.frame(df1[,3], df2[,3], df3[,3])

new_lst <- list(new_df1, new_df2, new_df3)

Is there a more compact way of doing this with large lists containing large data frames? Thanks in advance.

Upvotes: 3

Views: 39

Answers (2)

Humpelstielzchen
Humpelstielzchen

Reputation: 6441

This is an option:

cols <- ncol(my_lst[[1]])

lapply(1:cols, function(x) do.call(cbind, lapply(my_lst, `[`, x)))

[[1]]
  a c b
1 0 1 0
2 0 1 1
3 1 0 0
4 1 0 0
5 1 1 1

[[2]]
  b b a
1 0 0 0
2 1 1 0
3 0 0 1
4 0 0 1
5 1 1 1

[[3]]
  c a c
1 1 0 1
2 1 0 1
3 0 1 0
4 0 1 0
5 1 1 1

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388807

A tidyverse option is to change the columns names, transpose and bind_cols

library(tidyverse)
my_lst %>%
  map(setNames, letters[1:3]) %>%
  purrr::transpose() %>%
  map(bind_cols)

#$a
# A tibble: 5 x 3
#     V1    V2    V3
#  <dbl> <dbl> <dbl>
#1     0     1     0
#2     0     1     1
#3     1     0     0
#4     1     0     0
#5     1     1     1

#$b
# A tibble: 5 x 3
#     V1    V2    V3
#  <dbl> <dbl> <dbl>
#1     0     0     0
#2     1     1     0
#3     0     0     1
#4     0     0     1
#5     1     1     1

#$c
# A tibble: 5 x 3
#     V1    V2    V3
#  <dbl> <dbl> <dbl>
#1     1     0     1
#2     1     0     1
#3     0     1     0
#4     0     1     0
#5     1     1     1

Upvotes: 1

Related Questions