Open In App

How to Find Unique Values and Sort Them in R

Last Updated : 07 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding and Sorting unique values is a common task in R for data cleaning, exploration, and analysis. In this article, we will explore different methods to find unique values and sort them in R Programming Language.

Using sort() with unique()

In this approach, we use the unique() function to find unique values in a vector and then use the sort() function to sort them.

R
sub <- c("MATH", "SCIENCE", "SCIENCE", "ENGLISH", "HINDI", "ENGLISH", "HINDI",
             "MATH","PHYSICS")

# Find unique values and sort them in ascending order
val <- sort(unique(sub))
print(val)

Output:

[1] "ENGLISH" "HINDI" "MATH" "PHYSICS" "SCIENCE"

Below are some of the ways by which we can find unique values and sort them sets in R

  1. Using duplicated() and order()
  2. Using table() for Frequency Counts
  3. Using distinct() and arrange() from dplyr Package

Method 1: Using duplicated() and order()

In this approach we use duplicated() to find unique rows in a dataframe and order() to sort them based on a specific column.

R
df <- data.frame(
  CustomerID = c(101, 102, 103, 101, 104),
  Amount = c(50, 30, 20, 50, 40)
)
df

# Remove duplicate customers
unique <- df[!duplicated(df$CustomerID), ]

# Sort by customers ID
sort_df <- unique[order(unique$CustomerID), ]
print(sort_df)

Output:

CustomerID Amount
1 101 50
2 102 30
3 103 20
4 101 50
5 104 40
CustomerID Amount
1 101 50
2 102 30
3 103 20
5 104 40

Method 2: Using table() from Frequency Counts

In this approach we use table() to get the frequency counts of unique values, and then sort them using the sort() function.

R
food <- c("Pizza", "Burger", "Pizza", "Salad", "Pizza", "Burger",
                              "Salad", "Pizza", "Burger")

# Get frequency counts of unique preferences
pre <- table(food)

# Sort preferences by count
sort_pre <- sort(pre, decreasing = TRUE)
print(sort_pre)

Output:

food
Pizza Burger Salad
4 3 2

Method 3: Using distinct() and arrange() from dplyr Package

In this method we use functions like distinct() and arrange() from dplyr package to find unique values and sort them using arrange() function.

R
library(dplyr)

df <- data.frame(
  Name = c("Vipul", "Jayesh", "Pratham", "Vipul"),
  Age = c(25, 30, 25, 35)
)

# Find unique values and sort them
sort <- df %>% distinct(Name) %>% arrange(Name)
print(sort)

Output:

Name
1 Jayesh
2 Pratham
3 Vipul


Next Article

Similar Reads