R unique() Function - Removing Duplicate Values
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:
-
x An input vector, data frame, or matrix.
Example
Remove duplicate values from a vector
x
<-
c
(
3
,
1
,
4
,
1
,
5
,
9
,
2
,
6
,
5
,
3
,
5
)
(
"Original vector:"
)
(
x
)
(
"After deduplication:"
)
(
unique
(
x
)
)
View element categories
classes
<-
c
(
"Group A"
,
"Group B"
,
"Group A"
,
"Group C"
,
"Group B"
,
"Group A"
,
"Group C"
)
(
"All categories:"
)
(
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
(
"Whether duplicate (second and later occurrences):"
)
(
duplicated
(
x
)
)
Find all duplicate values
dupes
<-
x
[
duplicated
(
x
)
]
(
"Repeated values:"
)
(
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