R语言中,如何对数据框的数据根据某个条件进行排序呢?如何根据多条件进行排序呢,类似Excel中的排序效果:
1. 示例数据R语言中鸢尾花的数据,数据有五列:
> names(iris) [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
前五行数据预览:
> head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa2. 使用R中自带函数order
** 第一列升序,然后是第三列升序**
这里的iris[,1]是数据的第一列
r1 = iris[order(iris[,1],iris[3]),] head(r1)
结果:
> # 第一列升序,然后是第三列升序 > r1 = iris[order(iris[,1],iris[3]),] > head(r1) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 14 4.3 3.0 1.1 0.1 setosa 39 4.4 3.0 1.3 0.2 setosa 43 4.4 3.2 1.3 0.2 setosa 9 4.4 2.9 1.4 0.2 setosa 42 4.5 2.3 1.3 0.3 setosa 23 4.6 3.6 1.0 0.2 setosa
如果想要第一列升序,第三列降序呢,在第三列前面加上一个符号:
r2 = iris[order(iris[,1],-iris[3]),] head(r2)
结果:
> # 第一列升序,然后是第三列降序 > r2 = iris[order(iris[,1],-iris[3]),] > head(r2) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 14 4.3 3.0 1.1 0.1 setosa 9 4.4 2.9 1.4 0.2 setosa 39 4.4 3.0 1.3 0.2 setosa 43 4.4 3.2 1.3 0.2 setosa 42 4.5 2.3 1.3 0.3 setosa 4 4.6 3.1 1.5 0.2 setosa3. 使用dplyr的arrange
R包dplyr的函数arrange,更简单,更简洁:
# 多条件排序:使用dplyr::arrange
library(dplyr)
data("iris")
head(iris)
# 第一列升序,然后是第三列升序
arrange(iris,iris[,1],iris[,3])
# 第一列升序,然后是第三列降序
arrange(iris,iris[,1],-iris[,3])
结果:
> # 多条件排序:使用dplyr::arrange
> library(dplyr)
> data("iris")
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
>
> # 第一列升序,然后是第三列升序
> head(arrange(iris,iris[,1],iris[,3]))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 4.3 3.0 1.1 0.1 setosa
2 4.4 3.0 1.3 0.2 setosa
3 4.4 3.2 1.3 0.2 setosa
4 4.4 2.9 1.4 0.2 setosa
5 4.5 2.3 1.3 0.3 setosa
6 4.6 3.6 1.0 0.2 setosa
>
> # 第一列升序,然后是第三列降序
> head(arrange(iris,iris[,1],-iris[,3]))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 4.3 3.0 1.1 0.1 setosa
2 4.4 2.9 1.4 0.2 setosa
3 4.4 3.0 1.3 0.2 setosa
4 4.4 3.2 1.3 0.2 setosa
5 4.5 2.3 1.3 0.3 setosa
6 4.6 3.1 1.5 0.2 setosa
而且,arrange,可以直接输入列名,进行排序:
head(arrange(iris,Sepal.Length, -Petal.Length))
结果:
> head(arrange(iris,Sepal.Length, -Petal.Length)) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 4.3 3.0 1.1 0.1 setosa 2 4.4 2.9 1.4 0.2 setosa 3 4.4 3.0 1.3 0.2 setosa 4 4.4 3.2 1.3 0.2 setosa 5 4.5 2.3 1.3 0.3 setosa 6 4.6 3.1 1.5 0.2 setosa



