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
  • 763
  • 7
  • 26

4 Answers4

3

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

user2974951
  • 9,535
  • 1
  • 17
  • 24
2

Another option using diff and which.

v[c(1, which(diff(v) != 0) + 1)]
#[1] 3 1 3 2 3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

Another option is with lag:

library(dplyr)
v[v!=lag(v, default=1)]
[1] 3 1 3 2 3
TarJae
  • 72,363
  • 6
  • 19
  • 66
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
  • 874,273
  • 37
  • 540
  • 662