To count unique values from column of data frame in R, there are two different methods one is length() function with unique() function and other is summarise() function from dplyr package.

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

Method 1: Use length() and unique() Functions

length(unique(df$column_name))

Method 2: Use summarise() Function

library(dplyr)

df %>%
 summarise(count=n_distinct(df$column_name))

The following examples show how to count unique values from column of data frame in R.

Count Unique Values in Column Using length() and unique() Function in R

Let’s see how we can use length() and unique() function to count unique values from column of data frame:

# 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"))

# Get count of unique values
u <- length(unique(df$Machine_name))

# Print count
print(u)

Output:

[1] 8

Here the output shows 8 unique values in Machine_name column of data frame.

Count Unique Values in Column Using summarise() Function from dplyr Package in R

Let’s see how we can use summarise() function from dplyr package to count unqie values in column of data frame:

# Import library
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"))

# Get count of unique values
u <- df %>%
  summarise(count=n_distinct(df$Machine_name))

# Print count
print(u)

Output:

  count
1     8

Here the output shows count of unique values in Machine_name column of data frame.