Reputation: 5169
I have the following list of list:
nfoo <- list(a = list(x = 1:3, y = 11:13), b = list(x = 1:3, y = 100:102))
It looks like this:
> nfoo
$a
$a$x
[1] 1 2 3
$a$y
[1] 11 12 13
$b
$b$x
[1] 1 2 3
$b$y
[1] 100 101 102
What I want to do is to combine the list within the list, resulting:
$a
[1] 1 2 3 11 12 13
$b
[1] 1 2 3 100 101 102
How can I achieve that?
Upvotes: 2
Views: 67
Reputation: 72623
Using do.call
.
Map(do.call, nfoo, w="c")
# $a
# x1 x2 x3 y1 y2 y3
# 1 2 3 11 12 13
#
# $b
# x1 x2 x3 y1 y2 y3
# 1 2 3 100 101 102
Upvotes: 1
Reputation: 42544
For the sake of completeness, there is another variant which uses Reduce()
within lapply()
lapply(nfoo, Reduce, f = c)
$a [1] 1 2 3 11 12 13 $b [1] 1 2 3 100 101 102
Upvotes: 1
Reputation: 269461
If we know that each of the sublists of foo
contain vectors x
and y
(which is true for the example in the question) then:
lapply(foo, with, c(x, y))
giving:
$a
[1] 1 2 3 11 12 13
$b
[1] 1 2 3 100 101 102
Upvotes: 2
Reputation: 1452
library(tidyverse)
nfoo%>%map(unlist)
# $a
# x1 x2 x3 y1 y2 y3
# 1 2 3 11 12 13
#
# $b
# x1 x2 x3 y1 y2 y3
# 1 2 3 100 101 102
Upvotes: 1
Reputation: 2945
Use lapply
to iterate through your list and then unlist
to make each into a vector:
lapply(nfoo, unlist)
Upvotes: 1
Reputation: 520918
Use lapply
with docall
and the concatenate function (which also works with lists):
output <- lapply(nfoo, function(x) do.call(c, x))
output
$a
x1 x2 x3 y1 y2 y3
1 2 3 11 12 13
$b
x1 x2 x3 y1 y2 y3
1 2 3 100 101 102
Upvotes: 1
Reputation: 388817
We can use lapply
with unlist
lapply(nfoo, unlist, use.names = FALSE)
#$a
#[1] 1 2 3 11 12 13
#$b
#[1] 1 2 3 100 101 102
Using purrr
, we can do that by using map
and flatten.*
library(purrr)
map(nfoo, flatten_int)
Upvotes: 3