Count number of unique levels of a variable

The following should do the job:

choices <- length(unique(iris$Species))

If we are using dplyr, n_distinct would get the number of unique elements in each column

library(dplyr)
iris %>%
      summarise_each(funs(n_distinct))
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1           35          23           43          22       3

If your need is to count the number of unique instances for each column of your data.frame, you can use sapply:

sapply(iris, function(x) length(unique(x)))
#### Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
####  35           23          43            22               3

For just one specific colum, the code suggested by @Imran Ali (in the comments) is perfectly fine.

Tags:

R

Dataframe