在 R 编程中按对象的索引值对对象的元素进行排序 - order()函数
R 语言中的order()
函数用于按对象的索引值对对象进行排序。这些对象可以是向量、矩阵或数据帧。此函数接受布尔值作为参数以升序或降序排序。
Syntax:
order(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 by index values
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
# Calling order() function
order(x)
输出:
[1] 8 7 6 5 3 2 9 1 4 10
示例 2:
# R program to sort a vector by index values
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
# Calling order() function
# to sort in decreasing order
order(x, decreasing = TRUE)
# Calling order() function
# to print NA at the end
order(x, na.last = TRUE)
输出:
[1] 4 1 9 2 3 5 6 7 8 10
[1] 8 7 6 5 3 2 9 1 4 10