R语言 Unique()函数
R编程语言 中的 Unique()函数 用于返回一个没有任何重复元素/行的向量、数据框或数组。
语法: unique(x, incomparables, fromLast, nmax, …, MARGIN)
参数: 这个函数接受一些参数,如下图所示。
- x: 这个参数是一个向量、一个数据框、一个数组或NULL。
- incomparables: 这个参数是一个不能被比较的值的向量。如果它的值是FALSE,这意味着所有的值都可以被比较,而且可能是除默认值以外的方法所接受的唯一值。它将在内部被强制为与x相同的类型。
- fromLast: 这个参数表示是否应该从最后一个开始考虑重复,也就是说,相同的元素中最右边的将被保留。它的值是逻辑性的,即要么是真,要么是假。
- nmax: 这个参数表示 ,预期的最大的唯一项目数量。
- ...:这是特定方法的参数。
- MARGIN: 该参数表示 ,数组的余量要保持固定。
返回值: 该函数返回一个没有任何重复元素/行的向量、数据框或数组。
例子1:指定向量中的唯一元素
下面的例子显示了从指定向量中返回唯一元素的过程。
# R program to illustrate
# unique() function
# Initializing an input vector with some
# duplicate values
A <- c(1, 2, 3, 3, 2, 5, 6, 7, 6, 5)
# Calling the unique() function over the
# above vector to remove duplicate values
unique(A)
输出:
[1] 1 2 3 5 6 7
例2:从指定的矩阵中获得唯一的元素
下面的例子显示了从指定矩阵中返回唯一元素的过程。
# R program to illustrate
# unique() function
# Creating a 2*5 matrix with 10
df<-matrix(rep(1:5,length.out=10),
nrow = 2,ncol=5,byrow = T)
print("Original df:")
# Getting the matrix along with repeated
# elements
df
print("After using Unique:")
# Calling the unique() function to
# remove the duplicate values and
# Getting the matrix with unique elements
unique(df)
输出
[1] "Original df:"
1 2 3 4 5
1 2 3 4 5
[1] "After using Unique:"
1 2 3 4 5
例3:从指定的数据框架中获取唯一元素
下面的例子显示了从指定的数据框架中返回独特元素的过程。
# R program to illustrate
# unique() function
# Creating a data frame
Class_data <- data.frame(Student = c('Aman', 'Sita',
'Aman', 'Rohan',
'Sita'),
Age = c(22, 23, 22, 22, 23), Gender = c('Male', 'Female',
'Male', 'Male',
'Female'))
# Getting the data frame along with the repeated
# elements
Class_data
# Printing new line
writeLines("\n")
# Calling the unique() function over the above
# data frame to remove repeated elements and print
# the unique elements only
unique(Class_data)
输出
Student Age Gender
1 Aman 22 Male
2 Sita 23 Female
3 Aman 22 Male
4 Rohan 22 Male
5 Sita 23 Female
Student Age Gender
1 Aman 22 Male
2 Sita 23 Female
4 Rohan 22 Male
例4:从给定的数据框架中获取某一列的唯一元素
下面的例子显示了从给定的数据框架中返回一个特定列的唯一元素的过程。
# R program to illustrate
# unique() function
# Creating a data frame
data <- data.frame(x1 = c(9, 5, 6, 8, 9, 8),
x2 = c(2, 4, 2, 7, 1, 4),
x3 = c(3, 6, 7, 0, 3, 7),
x4 = c("Hello", "value", "value",
"geeksforgeeks", NA, "GFG")
)
# Calling the unique() function to extract
# the unique values from the particular
# columns of "x1" and "x2"
unique(data[c("x1")])
unique(data[c("x2")])
输出
x1
1 9
2 5
3 6
4 8
x2
1 2
2 4
4 7
5 1
例5:给定向量中的唯一元素
下面的例子显示了返回给定向量中唯一元素的长度的过程。
# R program to illustrate
# unique() function
# Initializing a vector
df <- c(1,2,3,4,5,6,7,4,5,6)
# Calling the unique() function
df_uniq <- unique(df)
# Calling the length function to
# return the length of unique values
# present in the above given vector
length(df_uniq)
输出
[1] 7