R: How to Find Unique Values in a Column


You can use the unique() function in R to find unique values in a column of a data frame.

This tutorial provides several examples of how to use this function with the following data frame:

#create data frame
df <- data.frame(team=c('A', 'A', 'B', 'B', 'C', 'C'),
                 points=c(90, 99, 90, 85, 90, 85),
                 assists=c(33, 33, 31, 39, 34, 34),
                 rebounds=c(30, 28, 24, 24, 28, 28))

#view data frame
df

  team points assists rebounds
1    A     90      33       30
2    A     99      33       28
3    B     90      31       24
4    B     85      39       24
5    C     90      34       28
6    C     85      34       28

Example 1: Find Unique Values in Column

The following code shows how to find unique values in the ‘team’ column:

#find unique values in 'team' column
unique(df$team)

[1] "A" "B" "C"

We can use similar syntax to find unique values in the ‘points’ column:

#find unique values in 'points' column
unique(df$points)

[1] 90 99 85

Example 2: Find & Sort Unique Values in Column

The following code shows how to find and sort unique values in the ‘points’ column:

#find and sort unique values in 'points' column
sort(unique(df$points))

[1] 85 90 99

We can also sort unique values in a descending order:

#find and sort unique values in 'points' column
sort(unique(df$points), decreasing=TRUE)

[1] 99 90 85

Example 3: Find & Count Unique Values in Column

The following code shows how to find and count the number of each unique value in the ‘points’ column:

#find and count unique values in 'points' column
table(df$points)

85 90 99 
 2  3  1 

From the output we can see:

  • The value 85 occurs 2 times.
  • The value 90 occurs 3 times.
  • The value 99 occurs 1 time.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Perform a COUNTIF Function in R
How to Find and Count Missing Values in R
How to Count Number of Occurrences in Columns in R

Leave a Reply

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