How to Find Unique Values in R

To find unique values in a column in a data frame, use the unique() function in R.

In Exploratory Data Analysis, the unique() function is crucial since it detects and eliminates duplicate values in the data.

Let’s look at how to get the unique data out of the R object.

Syntax

unique(data)

data: It is a vector / data frame /array / NULL.

The following data frame is used in this tutorial to demonstrate how to utilize this function.

Let’s create a data frame for illustration purposes,

data <- data.frame(Product=c('A', 'A', 'B', 'B', 'C', 'C'),
                 Likeability=c(80, 98, 80, 82, 70, 65),
                 Score=c(31, 30, 33, 33, 33, 23),
                 Quality=c(16, 24, 32, 56, 18, 12))

Let’s view the data frame

data
    Product Likeability Score Quality
1       A          80    31      16
2       A          98    30      24
3       B          80    33      32
4       B          82    33      56
5       C          70    33      18
6       C          65    23      12

Example 1: Find Unique Values in R

Use the unique() function to retrieve unique elements from a Vector, data frame, or array-like R object.

The unique() function in R returns a vector, data frame, or array-like object with duplicate elements and rows deleted.

The code below demonstrates how to locate unique values in the ‘Product’ column.

unique(data$Product)
[1] "A" "B" "C"

In the ‘Score’ column, we may use similar syntax to find unique values:

unique(data$Score)
[1] 31 30 33 23

Example 2: Find & Sort Unique Values in R

The code below demonstrates how to locate and sort unique values in the ‘Score’ column.

datatable editor-DT package in R » Shiny, R Markdown & R » finnstats

sort(unique(data$Score))
[1] 23 30 31 33

In addition, we can sort unique values in descending order

sort(unique(data$Score), decreasing=TRUE)
[1] 33 31 30 23

Example 3: Find & Count Unique Values in R

The code below demonstrates how to locate and count the number of each distinct value in the ‘Score’ column.

table(data$Score)
23 30 31 33
 1  1  1  3

The numbers 23, 30, and 31 appear once, whereas the number 33 appears three times, according to the above output.

Conclusion

In a vector, data frame, or array, the unique() function removes duplicate elements/rows.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − fourteen =