To count unique values by group in R, you can use two different function one way is group_by() and summarise() function from dplyr package. The other way to use unique() and length() function data.table package.

The following methods show how you can do it with syntax.

Method 1: Use dplyr Package

library(dplyr)

df %>%
  group_by(group_columm) %>%
  summarise(count = n_distinct(values_column))

Method 2: Use data.table Package

library(data.table)

df[, .(count = length(unique(values_column))), by = group_column]

The following examples show how to count uniqque values by group in R.

Count Unique Values by Group Using dplyr Package in R

Let’s see how we can use function from dplyr package to count unique values by group:

# Import package
library(dplyr)

# Create dafaframe
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
                 Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58,9.6,8.85,7.89,10.24,12.36,11.45,9.47,8.12),
                 Status=c("OK","Suspect","OK","OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))

# Count unique values by group
count <- df %>%
  group_by(Machine_name) %>%
  summarise(count = n_distinct(Status))

# Show count
print(count)  

Output:

  Machine_name count
  <chr>        <int>
1 A                1
2 B                2
3 C                1
4 D                2
5 E                1
6 F                1
7 G                1
8 H                1

Here the output shows count of unique values from Status column which group by Machine_name column of data frame.

Count Unique Values by Group Using data.table Package in R

Let’s see how we can use function from data.table package to count unique values by group:

# Import package
library(data.table)

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
                 Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58,9.6,8.85,7.89,10.24,12.36,11.45,9.47,8.12),
                 Status=c("OK","Suspect","OK","OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))

# Convert data frame to table
setDT(df)

# Count unique values by group
count1 <- df[, .(count = length(unique(Status))), by = Machine_name]

# Show count
print(count)

Output:

  Machine_name count
  <chr>        <int>
1 A                1
2 B                2
3 C                1
4 D                2
5 E                1
6 F                1
7 G                1
8 H                1

In the above code we use functions from data.table package and to use function we convert data frame into table. Here the output shows count of unique values from Status column which group by Machine_name column of data frame.