2

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

Jovan
  • 697
  • 6
  • 22

4 Answers4

3

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

user2974951
  • 7,144
  • 1
  • 13
  • 21
2

Another option using diff and which.

v[c(1, which(diff(v) != 0) + 1)]
#[1] 3 1 3 2 3
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
2

Another option is with lag:

library(dplyr)
v[v!=lag(v, default=1)]
[1] 3 1 3 2 3
TarJae
  • 43,365
  • 4
  • 14
  • 40
0

We can use rleid

library(data.table)
tapply(v, rleid(v), FUN = first)
1 2 3 4 5 
3 1 3 2 3 
akrun
  • 789,025
  • 32
  • 460
  • 575