如何按列的内容对 R DataFrame 进行排序?
在本文中,我们将讨论如何在 R 编程语言中按列的内容对 DataFrame 进行排序。我们可以使用 order()函数。带有提供的参数的 order()函数返回一个排列,将其第一个参数重新排列为升序或降序,通过进一步的参数打破联系。
Syntax: order(x, decreasing = TRUE/FALSE, na.last = TRUE or FALSE, method = c(“auto”, “shell”, “quick”, “radix”))
Parameters:
- x: data-frames, matrices, or vectors
- decreasing: TRUE then sort in descending order / FALSE then sort in ascending order.
- na.last: TRUE then NA indices are put at last / FALSE then NA indices are put first.
- method: sorting method.
Return: returns a permutation that rearranges its first argument into ascending or descending order of the data frame, vector, matrix, etc.
示例 1:
R
gfg_data <- data.frame(
Country = c("France","Spain","Germany","Spain","Germany",
"France","Spain","France","Germany","France"),
age = c(44,27,30,38,40,35,52,48,45,37),
salary = c(6000,5000,7000,4000,8000),
Purchased=c("No","Yes","No","No","Yes","Yes","No","Yes",
"No","Yes")
)
gfg_data[order(gfg_data$Country),]
R
gfg_data <- data.frame(
Country = c("France","Spain","Germany","Spain","Germany",
"France","Spain","France","Germany","France"),
age = c(44,27,30,38,40,35,52,48,45,37),
salary = c(6000,5000,7000,4000,8000),
Purchased=c("No","Yes","No","No","Yes","Yes","No","Yes",
"No","Yes")
)
gfg_data[order(gfg_data$age),]
输出:
示例2:
电阻
gfg_data <- data.frame(
Country = c("France","Spain","Germany","Spain","Germany",
"France","Spain","France","Germany","France"),
age = c(44,27,30,38,40,35,52,48,45,37),
salary = c(6000,5000,7000,4000,8000),
Purchased=c("No","Yes","No","No","Yes","Yes","No","Yes",
"No","Yes")
)
gfg_data[order(gfg_data$age),]
输出: