Unique Function in R

unique function in R –unique(), eliminates duplicate elements/rows from a vector, data frame or array.

Syntax for unique function in R:


if x is a vector or a data frame, returns a similar object but with the duplicate elements eliminated

Example of Unique function in R:

## unique of a vector

in the above example duplicate occurrence of 5,6,7,8,9 and 10 are eliminated and made to occur only once, so the output will be

[1]  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

Unique function for a column in a data frame:

## unique of a column in a data frame

In the above example we used the mtcars data frame and found the unique values of gear column in mtcars data frame. Instead of 32 entries it gives only 3 unique entries in the gear column

[1]  4   3   5


Unique function for a data frame in R: 

Unique function in R can also be applicable for data frame, matrices, and arrays. Let’s see an example on how to use unique function to identify unique elements in a data frame in R

# simple Data frame creation
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

so the resultant data frame will be

    a    b

1   A    1

2   A    1

3   A    2

4   B   4

5   B   1

6   B   1

7   C   2

8   C   2

  When we apply unique function to the above data frame

## Apply unique function for data frame in R

Duplicate entries in the data frame are eliminated and the final output will be

     a    b
1   A   1
3   A   2
4   B   4
5   B   1
7   C   2


previous small unique function in r                                                                                                                next small unique function in R