Home » How to Count Unique Values by Group in R (With Examples)

How to Count Unique Values by Group in R (With Examples)

by Tutor Aspire

You can use the following methods to count the number of unique values by group in R:

Method 1: Using Base R

results function(x) length(unique(x)))

Method 2: Using dplyr

library(dplyr)

results %
  group_by(group_var) %>%
  summarize(count = n_distinct(values_var))

Method 3: Using data.table

library(data.table)

df length(unique(values_var))), by = group_var]

Each method returns the exact same result, but the base R method tends to be significantly slower when working with large data frames.

The following examples show how to use each of these methods in practice with the following data frame:

#create data frame
df frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'),
                 points=c(10, 10, 14, 14, 18, 19, 20, 20, 20))

#view data frame
df

  team points
1    A     10
2    A     10
3    A     14
4    A     14
5    B     18
6    B     19
7    C     20
8    C     20
9    C     20

Method 1: Count Unique Values by Group Using Base R

The following code shows how to count the number of distinct points values for each team using base R:

#count unique points values by team
results function(x) length(unique(x)))

#view results
results

  team points
1    A      2
2    B      2
3    C      1

From the output we can see:

  • There are 2 unique points values for team A.
  • There are 2 unique points values for team B.
  • There is 1 unique points value for team C.

Method 2: Count Unique Values by Group Using dplyr

The following code shows how to count the number of distinct points values for each team using dplyr:

library(dplyr)

#count unique points values by team
results %
  group_by(team) %>%
  summarize(count = n_distinct(points))

#view results
results

# A tibble: 3 x 2
  team  count
1 A         2
2 B         2
3 C         1

Notice that these results match the ones from the base R method.

Method 3: Count Unique Values by Group Using data.table

The following code shows how to count the number of distinct points values for each team using data.table:

library(data.table)

#convert data frame to data table
df #count unique points values by team 
results length(unique(points))), by = team]

#view results
results

   team count
1:    A     2
2:    B     2
3:    C     1

Notice that these results match the ones from the previous two methods.

Additional Resources

The following tutorials explain how to perform other common operations using dplyr:

How to Recode Values Using dplyr
How to Replace NA with Zero in dplyr
How to Rank Variables by Group Using dplyr
How to Select the First Row by Group Using dplyr

You may also like