# r - 如何通过column排序dataframe

``````
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))
dd
b x y z
1 Hi A 8 1
2 Med D 3 1
3 Hi A 9 1
4 Low C 9 2

``````

``````
R> dd[with(dd, order(-z, b)), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1

``````

``````
R> 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
R>

``````

``````
## The data.frame way
dd[with(dd, order(-z, b)), ]

## The data.table way: (7 fewer characters, but that's not the important bit)
dd[order(-z, b)]

``````

``````
quarterlyreport[with(quarterlyreport,order(-z,b)),]

``````

``````
quarterlyreport[with(lastquarterlyreport,order(-z,b)),]

``````

`data.table` 中，我们关心的是像这样的微小细节。 所以我们做了一些简单的事情来避免输入变量名两次。 非常简单。`i``dd`的框架中已经被评估，自动。 你根本不需要 `with()`

``````
dd[with(dd, order(-z, b)), ]

``````

``` ```
dd[order(-z, b)]

``` ```

``````
quarterlyreport[with(lastquarterlyreport,order(-z,b)),]

``````

``````
quarterlyreport[order(-z,b)]

``````

``````
> sort(dd,by = ~ -z + b)
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1

``````

``````
library(dplyr)
# sort mtcars by mpg, ascending... use desc(mpg) for descending
arrange(mtcars, mpg)
# sort mtcars first by mpg, then by cyl, then by wt)
arrange(mtcars , mpg, cyl, wt)

``````

``````
arrange(dd, desc(z), b)

b x y z
1 Low C 9 2
2 Med D 3 1
3 Hi A 8 1
4 Hi A 9 1

``````

``````
newdata <- A[order(-A\$x),]

``````

``````
newdata <- A[order(-A\$x, A\$y, -A\$z),]

``````

``````
dd <- dd[with(dd, order(-z, b)), ]

``````