R + combine a list of vectors into a single vector

Rachit Agrawal picture Rachit Agrawal · Mar 20, 2013 · Viewed 53.6k times · Source

I have a single list of numeric vector and I want to combine them into one vector. But I am unable to do that. This list can have one element common across the list element. Final vector should not add them twice. Here is an example:

>lst
`1`
[1] 1 2
`2`
[2] 2 4 5
`3`
[3] 5 9 1

I want final result as this

>result
[1] 1 2 4 5 9 1

I tried doing following things, without worrying about the repition:

>vec<-vector()
>sapply(lst, append,vec)

and

>vec<-vector()
>sapply(lst, c, vec)

None of them worked. Can someone help me on this?

Thanks.

Answer

Rachit Agrawal picture Rachit Agrawal · Mar 21, 2013

A solution that is faster than the one proposed above:

vec<-unlist(lst)
vec[which(c(1,diff(vec)) != 0)]