Question

Suppose I have a list a built as follows:

a1<-list(1,2,list("X",10))
a2<-list("A",list("B"),"C")
a3<-list(list("D",list("E")),3.14)
a<-list(a1,a2,a3)

How can I transform a into this:

list(1,2,list("X",10),"A",list("B"),"C",list("D",list("E")),3.14)

I want a solution that works for arbitrary number of a1, a2, a3... an, not only for a1, a2 and a3 as in example above.

In Mathematica I would simply use Flatten[a,1], but how does one do it in R?

Was it helpful?

Solution

Use unlist with recursive=FALSE:

dput(unlist(a,recursive=FALSE))
list(1, 2, list("X", 10), "A", list("B"), "C", list("D", list(
    "E")), 3.14)

OTHER TIPS

do.call('c', a) will be faster then Reduce('c', a). unlist(a, recursive = FALSE, use.names = FALSE) will be faster then unlist(a, recursive = FALSE). unlist is the way to go in this case.

Would post as a comment but I dont appear to be able.

It's simple:

Reduce("c",a)

That's all.

Is unlist(a, recursive=FALSE) what you're looking for?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top