Lukasz
Lukasz

Reputation: 2317

flatten a list while concatenating

Is there an easy way to flatten a list of lists while concatenating. My question is probably best explained with an example.

When i execute the following code.

> a <- c(list(list(a=1,b=2), list(a=3,b=4)), list(a=5,b=6))
> print(a)

[[1]]
[[1]]$a
[1] 1

[[1]]$b
[1] 2


[[2]]
[[2]]$a
[1] 3

[[2]]$b
[1] 4


$a
[1] 5

$b
[1] 6

I would love to get the same result as if i would do this.

> a <- c(list(a=1,b=2), list(a=3,b=4), list(a=5,b=6))
> print(a)
$a
[1] 1

$b
[1] 2

$a
[1] 3

$b
[1] 4

$a
[1] 5

$b
[1] 6

Upvotes: 0

Views: 86

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

I guess you could use unlist or rapply, but I'd be wary of anything with duplicated names:

as.list(unlist(a))
# $a
# [1] 1
# 
# $b
# [1] 2
# 
# $a
# [1] 3
# 
# $b
# [1] 4
# 
# $a
# [1] 5
# 
# $b
# [1] 6

as.list(rapply(a, unlist)) should also work--not sure if there's an advantage to using that or not....


A (possibly) better idea would be to look at this LinearizeNestedList function I came across, which would let you flatten a list, but assigns names such that you can identify where they would have been in the first place.

After loading it in your workspace, usage would simply be:

LinearizeNestedList(a)

Upvotes: 4

Related Questions