Reputation: 2502
I am looking to count the number of unique elements in a vector, but excluding NA elements.
Basically, I want to use something like length(unique(x))
with an na.rm=TRUE argument, so that if I have length(unique(c(1,2,3,NA,2)))
will return 3
I tried data.table uniqueN
but this also doesn't have this option. Is there a quick and easy way to do this, instead of having to do two separate operations on the column?
Upvotes: 17
Views: 16484
Reputation: 78600
You can use na.omit
first:
x <- c(1,2,3,NA,2)
length(unique(na.omit(x)))
Alternatively, n_distinct
from dplyr has an na_rm
argument:
library(dplyr)
n_distinct(x, na.rm = TRUE)
Upvotes: 36