R编程中向量的排序——sort()函数
R 语言中的sort()
函数用于按向量的值对向量进行排序。它以布尔值作为参数以升序或降序排序。
Syntax:
sort(x, decreasing, na.last)
Parameters:
x: Vector to be sorted
decreasing: Boolean value to sort in descending order
na.last: Boolean value to put NA at the end
示例 1:
# R program to sort a vector
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
# Calling sort() function
sort(x)
输出:
[1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0
示例 2:
# R program to sort a vector
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
# Calling sort() function
# to print in decreasing order
sort(x, decreasing = TRUE)
# Calling sort() function
# to print NA at the end
sort(x, na.last = TRUE)
输出:
[1] 9.0 7.0 6.0 4.0 3.0 1.2 -4.0 -5.0 -8.0
[1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0 NA