Allen Wang
Allen Wang

Reputation: 2502

number of unique elements excluding NA in r

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

Answers (2)

David Robinson
David Robinson

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

Matt Dowle
Matt Dowle

Reputation: 59602

data.table::uniqueN has na.rm in version v1.9.7+.

Upvotes: 6

Related Questions