R order() Function - Get Sort Indices

R 语言实例R Language Examples

The R order() function returns the index positions of each element in the original vector after sorting.

Unlike sort(), which returns the sorted values, order() returns the permutation of the sort, which is very useful in data frame sorting.

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

order(x, decreasing = FALSE, na.last = TRUE)

Parameter description:

  • xInput vector (multiple vectors can be passed for multi-condition sorting).

  • decreasingWhether to sort in descending order, default FALSE.

  • na.lastNA value placement.

Example

x <- c(50, 20, 30, 10, 40)
names(x) <- c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi")

# order returns sort indices
idx <- order(x)
print("Sorted indices:")
print(idx)

# Use indices to get sorted values and corresponding names
print("By score ascending:")
print(x[idx])

# sort directly returns sorted values (comparison)
print("sort direct result:")
print(sort(x))

Executing the above code produces the following result:

[1] "排序后的索引:"
[1] 4 2 3 5 1
[1] "按成绩升序:"
赵六 李四 王五 钱七 张三
  10   20   30   40   50
[1] "sort 直接结果:"
赵六 李四 王五 钱七 张三
  10   20   30   40   50

order() is very practical for sorting data frames:

Example

# Create data frame
df <- data.frame(
Name= c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi"),
Age= c(25, 30, 22, 28, 26),
Score= c(88, 92, 76, 85, 90)
)

# Sort by score descending
df_sorted <- df[order(df$Score, decreasing= TRUE), ]
print("Sorted by score descending:")
print(df_sorted)

# Multi-condition sorting: first by age, then by score
df_sorted2 <- df[order(df$Age,df$score), ]
print("First by age, then by score:")
print(df_sorted2)

Executing the above code produces the following result:

[1] "按成绩降序排列:"
  姓名 年龄 成绩
2 李四   30   92
5 钱七   26   90
1 张三   25   88
4 赵六   28   85
3 王五   22   76
[1] "先按年龄再按成绩:"
  姓名 年龄 成绩
3 王五   22   76
1 张三   25   88
5 钱七   26   90
4 赵六   28   85
2 李四   30   92

R 语言实例R Language Examples

Other Extensions