Rachit Agrawal Rachit Agrawal - 1 month ago 4
R Question

R + combine a list of vectors into a single vector

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

A solution that is faster than the one proposed above:

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

This is faster than the one proposed above.