'In R, transform a vector with repeated values to a vector of single ordered values including the repetitions?
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.
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | utubun |
