Test if a value is unique in a vector in R
The match operator %in%
is very helpful.
!test %in% test[duplicated(test)]
Your original suggestion to use duplicated()
's fromLast = TRUE
switch combined with an OR operator seems a simple and elegant solution:
test <- c(1:5, 3:7)
test
## [1] 1 2 3 4 5 3 4 5 6 7
duplicated(test) # incorrect result
## [1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE
duplicated(test) | duplicated(test, fromLast = TRUE) # correct result
## [1] FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE
This play's nice when using data.table to perform operations by group, where the syntax makes it ambiguous if your variable name is the row value or the group column vector.