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?
Using std::remove function A simple solution is to iterate the vector, and for each element, we delete all its duplicates from the vector if present. We can either write our own routine for this or use the std::remove algorithm that makes our code elegant. This approach takes constant space but runs in O(n2) time.
You can check out unique
function.
> v = c(1, 1, 5, 5, 2, 2, 6, 6, 1, 3) > unique(v) [1] 1 5 2 6 3
This does the same thing. Slower, but useful if you also want a logical vector of the duplicates:
v[duplicated(v)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With