R + combine a list of vectors into a single vector

Solution 1:

A solution that is faster than the one proposed above:

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

Solution 2:

Another answer using Reduce().

Create the list of vectors:

lst <- list(c(1,2),c(2,4,5),c(5,9,1))

Combine them into one vector

vec <- Reduce(c,lst)
vec
# [1] 1 2 2 4 5 5 9 1

Keep the repeated ones only once:

unique(Reduce(c,lst))
#[1] 1 2 4 5 9

If you want to keep that repeated one at the end, You might want to use vec[which(c(1,diff(vec)) != 0)] as in @Rachid's answer

Solution 3:

You want rle:

rle(unlist(lst))$values

> lst <- list(`1`=1:2, `2`=c(2,4,5), `3`=c(5,9,1))
> rle(unlist(lst))$values
## 11 21 22 31 32 33 
##  1  2  4  5  9  1