R how to remove repeated value while save unique values in running length

Viewed 44

So Example I have this vectors:

v <- c(3,3,3,3,3,1,1,1,1,1,1,
3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,2,2,2,2,2,2,2,3,3,
3,3,3,3,3,3,3,3,3,3,3)

And I like to Simplify the vectors as this expected outputs:

exp_output <- c(3,1,3,2,3)

Whats the best and convenient way to do this? Thankyou

4 Answers

Try rle(v)$values which results in [1] 3 1 3 2 3.

Another option using diff and which.

v[c(1, which(diff(v) != 0) + 1)]
#[1] 3 1 3 2 3

Another option is with lag:

library(dplyr)
v[v!=lag(v, default=1)]
[1] 3 1 3 2 3

We can use rleid

library(data.table)
tapply(v, rleid(v), FUN = first)
1 2 3 4 5 
3 1 3 2 3 
Related