R unique() function - Remove duplicate values

R 语言实例R Language Examples

The R unique() function is used to remove duplicate values from vectors or data frames and returns unique elements.

unique() is very commonly used in data cleaning and checking categorical levels.

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

unique(x)

Parameter description:

  • xInput vector, data frame, or matrix.

Example

# Remove duplicate values from 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))

Executing the above code outputs the following result:

[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() indicates whether it is a duplicate
print("Whether it is a duplicate (appearing second and later):")
print(duplicated(x))

# Find all duplicate values
dupes <- x[duplicated(x)]
print("Duplicate values:")
print(unique(dupes))

Executing the above code outputs the following result:

[1] "是否为重复(第二个及之后出现):"
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
 [9]  TRUE  TRUE  TRUE
[1] "重复出现的值:"
[1] 1 5 3

R 语言实例R Language Examples

Other Extensions