R语言 如何通过列的内容对R数据框架进行排序
在这篇文章中,我们将讨论如何在R编程语言中根据列的内容对DataFrame进行排序。我们可以使用order()函数来实现。order()函数使用所提供的参数返回一个排列组合,将其第一个参数重新排列成升序或降序,并通过进一步的参数打破联系。
语法: order(x, decreasing = TRUE/FALSE, na.last = TRUE or FALSE, method = c(“auto”, “shell”, “quick”, “radix”)
参数
- x:数据帧、矩阵或向量
- decreasing :TRUE则按降序排序/FALSE则按升序排序。
- na.last。TRUE,则将NA指数放在最后/FALSE,则将NA指数放在前面。
- method:排序方法。
返回: 返回一个将其第一个参数重新排列成数据框、向量、矩阵等的升序或降序的排列方式。
示例1 :
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),]
输出
例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),]
输出