I have a vector with repeated elements, and would like to remove them so that each element appears only once.
In Python I could construct a Set
from a vector to achieve this, but how can I do this in R?
I have a vector with repeated elements, and would like to remove them so that each element appears only once.
In Python I could construct a Set
from a vector to achieve this, but how can I do this in R?
You can check out
unique
function.This does the same thing. Slower, but useful if you also want a logical vector of the duplicates:
To remove contiguous duplicated elements only, you can compare the vector with a shifted version of itself:
The same can be written a little more elegantly using dplyr:
The NA returned by
lag()
removes the first value, to keep the first value, you can change the default to a value that will be different from the first value.