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?
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.
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.
setequal() function in R Language is used to check if two objects are equal.
The match operator %in%
is very helpful:
!test %in% test[duplicated(test)]
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