Home > Software design >  In R, transform a vector with repeated values to a vector of single ordered values including the rep
In R, transform a vector with repeated values to a vector of single ordered values including the rep

Time:05-15

I have a vector x <- c(5, 5, 5, 3, 2, 2, 5, 5, 2). I need to get a new vector with the ordered distinct (but duplicates allowed) values: y <- c(5, 3, 2, 5, 2)

I'm sure it's a trivial problem but I've been looking around and I don't see a simple way to do it.

CodePudding user response:

Just out of the curiosity, I've tried to solve it without rle(x)$values:

x[x != c(x[-1], Inf)]
# [1] 5 3 2 5 2

Basically we are just comparing the original vector, and its' shifted to the left version, to create a subset index. So if the current element is equal to the next element, we return FALSE to remove this element from the initial vector.

555322552
|||||||||
55322552i
|||||||||
001101011
|||||||||
xx53x2x52

result: 53252

We always return the last element (hopefully, there are no NAs or NULLs).

  •  Tags:  
  • r
  • Related