Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a value is unique in a vector in R

Tags:

r

unique

vector

Let's assume the following example:

test<-c(1:5,3:7)

which gives

test
[1] 1 2 3 4 5 3 4 5 6 7

I would like to have an easy function that returns TRUE if the value is unique within the vector.

[1] TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE

What I tried:

unique(test) only gives me back the unique values including those who are duplicated. duplicated(test) gives me back

[1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE TRUE FALSE FALSE

which is obviously not the required result since the function tests for duplicated observations in sequence and the first occurrence is not counted as a duplicate. I could of course reverse the control sequence by including fromLast = T and create two vectors. Out of these two I could create a third that indicates true unique values...but this is rather to complicated.

table(test) allows me to compute the occurrence of each value

test
1 2 3 4 5 6 7 
1 1 2 2 2 1 1 

which brings me closer to what i want, but is still not the required result (a vector of the same length indicating whether it is unique within the vector or not.)


so anybody any idea how to do it easier?

like image 327
joaoal Avatar asked Aug 21 '15 22:08

joaoal


People also ask

How do I find unique values in a vector in R?

Use the unique() function to retrieve unique elements from a Vector, data frame, or array-like R object. The unique() function in R returns a vector, data frame, or array-like object with duplicate elements and rows deleted.

What is unique () in R?

The unique() function in R is used to eliminate or delete the duplicate values or the rows present in the vector, data frame, or matrix as well.

How do you check if values are the same in R?

setequal() function in R Language is used to check if two objects are equal.


1 Answers

The match operator %in% is very helpful:

!test %in% test[duplicated(test)]
like image 198
CSJCampbell Avatar answered Oct 01 '22 17:10

CSJCampbell