Home > Blockchain >  Transposing elements of a list in R
Transposing elements of a list in R

Time:12-24

I have this list:

list1 <- list(A = c("A1", "B1", "C1"), B = c("A2", "B2", "C2"), D = c("A3", "B3", "C3"))
list2 <- list(A = c("D1", "E1", "F1"), B = c("D2", "E2", "F2"), D = c("D3", "E3", "F3"))
list3 <- list(A = c("G1", "H1", "I1"), B = c("G2", "H2", "I2"), D = c("G3", "H3", "I3"))
my_list <- list(list1, list2, list3)

I'd like to turn it into this list:

list1a <- list(A = c("A1", "B1", "C1"), B = c("D1", "E1", "F1"), D = c("G1", "H1", "I1"))
list2a <- list(A = c("A2", "B2", "C2"), B = c("D2", "E2", "F2"), D = c("G2", "H2", "I2"))
list3a <- list(A = c("A3", "B3", "C3"), B = c("D3", "E3", "F3"), D = c("G3", "H3", "I3"))
my_new_list <- list(list1a, list2a, list3a)

What's the most efficient solution using base R functions?

CodePudding user response:

One option

sapply(1:length(my_list),function(x){lapply(my_list,"[[",x)},simplify=F)

[[1]]
[[1]][[1]]
[1] "A1" "B1" "C1"

[[1]][[2]]
[1] "D1" "E1" "F1"

[[1]][[3]]
[1] "G1" "H1" "I1"
...

CodePudding user response:

purrr has the tranpose function for this:

library(purrr)
my_list_t <- transpose(my_list)

str(my_list_t)

giving:

List of 3
 $ A:List of 3
  ..$ : chr [1:3] "A1" "B1" "C1"
  ..$ : chr [1:3] "D1" "E1" "F1"
  ..$ : chr [1:3] "G1" "H1" "I1"
 $ B:List of 3
  ..$ : chr [1:3] "A2" "B2" "C2"
  ..$ : chr [1:3] "D2" "E2" "F2"
  ..$ : chr [1:3] "G2" "H2" "I2"
 $ D:List of 3
  ..$ : chr [1:3] "A3" "B3" "C3"
  ..$ : chr [1:3] "D3" "E3" "F3"
  ..$ : chr [1:3] "G3" "H3" "I3"

Note that due to the balance that this could have been represented by an array in which case aperm could be used.

a <- array(unlist(my_list), c(3, 3, 3))
ap <- aperm(a, c(1, 3, 2))

all(a == unlist(my_list))
## [1] TRUE

all(ap == unlist(my_list_t))
## [1] TRUE
  •  Tags:  
  • r
  • Related