R + combine a list of vectors into a single vector

RListVectorAppendSapply

R Problem Overview


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.

R Solutions


Solution 1 - R

A solution that is faster than the one proposed above:

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

Solution 2 - R

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 - R

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 

Solution 4 - R

stack will do this nicely too, and looks more concise:

stack(lst)$values

Solution 5 - R

Benchmarking the two answers by Rachit and Martijn

rbenchmark::benchmark(
  "unlist" = {
    vec<-unlist(a)
    vec[which(diff(vec) != 0)]
  },
  "reduce" = {
    a %>% reduce(c) %>% unique
  }
)

Output:

    test replications elapsed relative user.self sys.self user.child sys.child
2 reduce          100   0.036        3     0.036    0.000          0         0
1 unlist          100   0.012        1     0.000    0.004          0         0

This one clearly beat the other one.

Solution 6 - R

Doing it the tidyverse way:

library(tidyverse)
lst %>% reduce(c) %>% unique

This uses the (uncapitalized) reduce version from purrr in combination with pipes. Also note that if the list contains named vectors, the final naming will be different depending on whether unlist or reduce methods are used.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRachit AgrawalView Question on Stackoverflow
Solution 1 - RRachit AgrawalView Answer on Stackoverflow
Solution 2 - RPaul RougieuxView Answer on Stackoverflow
Solution 3 - RMatthew LundbergView Answer on Stackoverflow
Solution 4 - R0mn1View Answer on Stackoverflow
Solution 5 - RPrradepView Answer on Stackoverflow
Solution 6 - RMartijnVanAttekumView Answer on Stackoverflow