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

Time:10-01

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

CodePudding user response:

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

CodePudding user response:

Another option using diff and which.

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

CodePudding user response:

Another option is with lag:

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