Split list of vectors in nth vectors in R

I have a list in R with three vectors inside, each of them having 32 numeric elements inside.

I would like to split this list, so that I can get 32 vectors of length 3, each one corresponding to the three first elements of the three vectors in the list, the three second elements of the three vectors and so on.

Say, my list has this aspect:

$`1`
 [1] 0.00000000 0.00000000 0.00000000 0.01538462 0.01538462 0.01538462 0.01538462 0.13846154 0.00000000 0.00000000
[11] 0.00000000 0.03076923 0.00000000 0.01538462 0.04615385 0.20000000 0.00000000 0.01538462 0.00000000 0.04615385
[21] 0.00000000 0.00000000 0.01538462 0.15384615 0.00000000 0.01538462 0.00000000 0.01538462 0.01538462 0.01538462
[31] 0.03076923 0.18461538

$`2`
 [1] 0.00000000 0.00000000 0.00000000 0.01428571 0.00000000 0.01428571 0.02857143 0.11428571 0.00000000 0.01428571
[11] 0.00000000 0.05714286 0.00000000 0.01428571 0.02857143 0.20000000 0.00000000 0.00000000 0.00000000 0.01428571
[21] 0.00000000 0.01428571 0.02857143 0.17142857 0.01428571 0.00000000 0.00000000 0.02857143 0.01428571 0.02857143
[31] 0.02857143 0.17142857

$`3`
 [1] 0.00000000 0.01408451 0.00000000 0.04225352 0.01408451 0.02816901 0.01408451 0.16901408 0.00000000 0.01408451
[11] 0.00000000 0.00000000 0.01408451 0.00000000 0.02816901 0.19718310 0.00000000 0.00000000 0.00000000 0.04225352
[21] 0.00000000 0.01408451 0.00000000 0.12676056 0.00000000 0.00000000 0.00000000 0.01408451 0.00000000 0.00000000
[31] 0.05633803 0.21126761

What I want to get is 32 vectors of length 3, say:

> 1
[1] 0.00000000 0.0000000 0.0000000
> 2
[1] 0.00000000 0.0000000 0.0000000
> 3
[1] 0.00000000 0.0000000 0.0000000
> 4
[1] 0.01538462 0.01428571 0.04225352

And so on...

Actually I have a list with more than three vectors inside, so I would like to do it no matter the number of vectors in the list, but those vectors are always of length 32.

I have been wondering for a while how to do it... but could not reach a solution...

Thanks

Upvotes: 0

Views: 59

Answers (2)

thc
thc

Reputation: 9705

Base R solution:

df <- do.call(rbind, my_list)

Then you can grab each set by the column number.

Upvotes: 3

akrun
akrun

Reputation: 887078

We can use transpose from purrr and then map to unlist the nested list to get the list of 32 vectors

library(tidyverse)
transpose(l1) %>% 
         map(unlist)

Upvotes: 1

Related Questions