Question

I have a list of named lists

t <- list(list(a=1,b=2,c=3), list(a=3, b=2, c=1), list(a=2, b=3, c=1))
[[1]]
[[1]]$a
[1] 1
[[1]]$b
[1] 2
[[1]]$c
[1] 3
[[2]]
[[2]]$a
[1] 3
[[2]]$b
[1] 2
[[2]]$c
[1] 1
[[3]]
[[3]]$a
[1] 2
[[3]]$b
[1] 3
[[3]]$c
[1] 1

and I would like to get a single named list or dataframe, like so

$a
[1] 1 3 2
$b
[1] 2 2 3
$c
[1] 3 1 1

Currently I am looping over list of named lists, adding each value to a new named list. How can I do this in a single line?

Was it helpful?

Solution

Maybe one of the following would work for you:

## As a data.frame
do.call(rbind, lapply(t, data.frame))
#   a b c
# 1 1 2 3
# 2 3 2 1
# 3 2 3 1

## As a list
as.list(do.call(rbind, lapply(t, data.frame)))
# $a
# [1] 1 3 2
# 
# $b
# [1] 2 2 3
#
# $c
# [1] 3 1 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top