Unique Values in Data Frame Variables in R (2 Examples)

In this R tutorial you’ll learn how to get the unique value (counts) in all data frame columns.

Creation of Example Data

data(iris)                                     # Example data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Example 1: Count Unique Values by Data Frame Column

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

Example 2: Display Unique Values by Data Frame Column

lapply(iris, unique)                           # Display unique values
# $Sepal.Length
#  [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.4 4.8 4.3 5.8 5.7 5.2 5.5 4.5 5.3 7.0 6.4 6.9 6.5 6.3 6.6 5.9 6.0 6.1 5.6 6.7 6.2 6.8 7.1 7.6 7.3 7.2 7.7 7.4 7.9
# 
# $Sepal.Width
#  [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 2.9 3.7 4.0 4.4 3.8 3.3 4.1 4.2 2.3 2.8 2.4 2.7 2.0 2.2 2.5 2.6
# 
# $Petal.Length
#  [1] 1.4 1.3 1.5 1.7 1.6 1.1 1.2 1.0 1.9 4.7 4.5 4.9 4.0 4.6 3.3 3.9 3.5 4.2 3.6 4.4 4.1 4.8 4.3 5.0 3.8 3.7 5.1 3.0 6.0 5.9 5.6 5.8 6.6 6.3 6.1 5.3 5.5 6.7 6.9 5.7 6.4 5.4 5.2
# 
# $Petal.Width
#  [1] 0.2 0.4 0.3 0.1 0.5 0.6 1.4 1.5 1.3 1.6 1.0 1.1 1.8 1.2 1.7 2.5 1.9 2.1 2.2 2.0 2.4 2.3
# 
# $Species
# [1] setosa     versicolor virginica 
# Levels: setosa versicolor virginica
#

Related Tutorials

Here, you may find some additional resources on topics such as matrices, counting, and character strings.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top