How to Find Unique Values and Sort Them in R
Last Updated :
01 Mar, 2024
In this article, we will explore different methods to find unique values and sort them in R Programming Language.
Find Unique Values and Sort Them in R
Below are some of the ways by which we can find unique values and sort them sets in R
- Using
sort()
with unique()
- Using
duplicated()
and order()
- Using
table()
for Frequency Counts
- Using distinct() and arrange() from dplyr Package
Find Unique Values and Sort Them 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
subject <- c ( "MATH" , "SCIENCE" , "SCIENCE" , "ENGLISH" , "HINDI" , "ENGLISH" , "HINDI" ,
"MATH" , "PHYSICS" )
sorted_unique_values <- sort ( unique (subject))
print (sorted_unique_values)
|
Output:
[1] "ENGLISH" "HINDI" "MATH" "PHYSICS" "SCIENCE"
Find Unique Values and Sort Them 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
customer_data <- data.frame (
CustomerID = c (101, 102, 103, 101, 104),
Amount = c (50, 30, 20, 50, 40)
)
customer_data
unique_customers <- customer_data[! duplicated (customer_data$CustomerID), ]
sorted_unique_customers <- unique_customers[ order (unique_customers$CustomerID), ]
print (sorted_unique_customers)
|
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
Find Unique Values and Sort Them 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_preferences <- c ( "Pizza" , "Burger" , "Pizza" , "Salad" , "Pizza" , "Burger" ,
"Salad" , "Pizza" , "Burger" )
preference_counts <- table (food_preferences)
sorted_preferences <- sort (preference_counts, decreasing = TRUE )
print (sorted_preferences)
|
Output:
food_preferences
Pizza Burger Salad
4 3 2
Find Unique Values and Sort Them 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)
)
sorted_unique_names <- df %>% distinct (Name) %>% arrange (Name)
print (sorted_unique_names)
|
Output:
Name
1 Jayesh
2 Pratham
3 Vipul
Conclusion
In R, we explored different methods to find unique values and sort them, All of them have their advantage depending on the specific requirements of your data analysis tasks. By understanding and implementing these methods, we can streamline our data processing workflow and extract valuable insights from your datasets in R.
Share your thoughts in the comments
Please Login to comment...