Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove repeated elements in a vector, similar to 'set' in Python

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?

like image 999
ashim Avatar asked May 26 '12 20:05

ashim


People also ask

How do you remove a repeating element from a vector?

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.


2 Answers

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 
like image 194
sus_mlm Avatar answered Oct 05 '22 13:10

sus_mlm


This does the same thing. Slower, but useful if you also want a logical vector of the duplicates:

v[duplicated(v)] 
like image 21
dardisco Avatar answered Oct 05 '22 13:10

dardisco