mylist = list(list(c(1, 2, 3, 4, 5), c(2, 3, 9)), list(c(1, 4, 2, 1, 3), c(2, 4, 3)))
> mylist
[[1]]
[[1]][[1]]
[1] 1 2 3 4 5
[[1]][[2]]
[1] 2 3 9
[[2]]
[[2]][[1]]
[1] 1 4 2 1 3
[[2]][[2]]
[1] 2 4 3
I have a list (or lists within list) where the first element is a vector of 5 values, and the second element is a vector of 3 values. I would like my output to be something like
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 4 2 1 3
for the first element and
[,1] [,2] [,3]
[1,] 2 3 9
[2,] 2 4 3
for the second element.
I've tried using do.call(rbind, mylist)
but that didn't seem to work since I have multiple elements. What's a way to convert this list to 2 data.frames or matrices?
Try this:
firstm<-sapply(X = mylist,"[[",1,simplify = T)
secondm<-sapply(X = mylist,"[[",2,simplify = T)
This will give you two matrices, when you provide the simplify = T
argument. To get the desired format you can use the transpose using t()
.
#> firstm
# [,1] [,2]
#[1,] 1 1
#[2,] 2 4
#[3,] 3 2
#[4,] 4 1
#[5,] 5 3
firstm<-t(firstm)
#> firstm
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 2 3 4 5
#[2,] 1 4 2 1 3
So close with your do.call
. Make it call Map
over your list objects, with rbind
as the function:
do.call(Map, c(rbind, mylist))
#[[1]]
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 2 3 4 5
#[2,] 1 4 2 1 3
#[[2]]
# [,1] [,2] [,3]
#[1,] 2 3 9
#[2,] 2 4 3
Here is an option using tidyverse
library(tidyverse)
mylist %>%
transpose %>%
map(unlist) %>%
map(matrix, nrow=2, byrow = TRUE)
#[[1]]
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 2 3 4 5
#[2,] 1 4 2 1 3
#[[2]]
# [,1] [,2] [,3]
#[1,] 2 3 9
#[2,] 2 4 3
Another way could be to strip the hierarchy from the list with the flatten
function in purrr
. So,
y <- flatten(mylist)
do.call(rbind, y[c(1,3)])
do.call(rbind, y[c(2,4)])
Output:
> do.call(rbind, y[c(1,3)])
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 4 2 1 3
> do.call(rbind, y[c(2,4)])
[,1] [,2] [,3]
[1,] 2 3 9
[2,] 2 4 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.