6.5 按列排序

在数据框内,根据(order)某一列或几列对行进行排序(sort),根据鸢尾花(iris)的类别(Species)对萼片(sepal)的长度进行排序,其余的列随之变化

# 先对花瓣的宽度排序,再对花瓣的长度排序
head(iris[order(iris$Species, iris$Petal.Width, iris$Petal.Length), ]) 
##    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 14          4.3         3.0          1.1         0.1  setosa
## 13          4.8         3.0          1.4         0.1  setosa
## 38          4.9         3.6          1.4         0.1  setosa
## 10          4.9         3.1          1.5         0.1  setosa
## 33          5.2         4.1          1.5         0.1  setosa
## 23          4.6         3.6          1.0         0.2  setosa

sort/ordered 排序, 默认是升序

dd <- data.frame(
  b = factor(c("Hi", "Med", "Hi", "Low"),
    levels = c("Low", "Med", "Hi"), ordered = TRUE
  ),
  x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
  z = c(1, 1, 1, 2)
)
str(dd)
## 'data.frame':    4 obs. of  4 variables:
##  $ b: Ord.factor w/ 3 levels "Low"<"Med"<"Hi": 3 2 3 1
##  $ x: chr  "A" "D" "A" "C"
##  $ y: num  8 3 9 9
##  $ z: num  1 1 1 2
dd[order(-dd[,4], dd[,1]), ]
##     b x y z
## 4 Low C 9 2
## 2 Med D 3 1
## 1  Hi A 8 1
## 3  Hi A 9 1

根据变量 z

dd[order(dd$z, dd$b), ]
##     b x y z
## 2 Med D 3 1
## 1  Hi A 8 1
## 3  Hi A 9 1
## 4 Low C 9 2