Search code examples
rvectorunique

Test if a value is unique in a vector in R


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?


Solution

  • The match operator %in% is very helpful:

    !test %in% test[duplicated(test)]