Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R unique() Function - Removing Duplicate Values

R unique() Function - Removing Duplicate Values

R Language Examples R Language Examples

The R unique() function is used to remove duplicate values from a vector or data frame, returning unique elements.

unique() is very commonly used in data cleaning and when viewing category levels.

The syntax of the unique() function is as follows:

unique(x)

Parameter Description:

Example

Remove duplicate values from a vector

x

<-

c

(

3

,

1

,

4

,

1

,

5

,

9

,

2

,

6

,

5

,

3

,

5

)

print

(

"Original vector:"

)

print

(

x

)

print

(

"After deduplication:"

)

print

(

unique

(

x

)

)

View element categories

classes

<-

c

(

"Group A"

,

"Group B"

,

"Group A"

,

"Group C"

,

"Group B"

,

"Group A"

,

"Group C"

)

print

(

"All categories:"

)

print

(

unique

(

classes

)

)

The output of the code above is:

[1] "原始向量:"

 [1] 3 1 4 1 5 9 2 6 5 3 5

[1] "去重后:"

[1] 3 1 4 5 9 2 6

[1] "所有类别:"

[1] "A组" "B组" "C组"

unique() combined with duplicated() can find which values are duplicates:

Example

x

<-

c

(

3

,

1

,

4

,

1

,

5

,

9

,

2

,

6

,

5

,

3

,

5

)

duplicated() marks whether a value is a duplicate

print

(

"Whether duplicate (second and later occurrences):"

)

print

(

duplicated

(

x

)

)

Find all duplicate values

dupes

<-

x

[

duplicated

(

x

)

]

print

(

"Repeated values:"

)

print

(

unique

(

dupes

)

)

The output of the code above is:

[1] "是否为重复(第二个及之后出现):"

 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

 [9]  TRUE  TRUE  TRUE

[1] "重复出现的值:"

[1] 1 5 3

R Language Examples R Language Examples