I have a dataframe which is consisted by two factor column. And I want to sort it by one column ascending and another descending. More specifically, I want to find equivalent R code to SQL "order by 1 asc, 2 desc"
Asked
Active
Viewed 2,564 times
2 Answers
1
You could also use the order
function with method = "radix"
which allows you to pass a vector for the argument decreasing
:
## Generate sample data:
set.seed(123)
dat <- data.frame(a = letters[sample(1:5, 20, replace = TRUE)],
b = rep(c("orange", "apple", "pear", "banana"), 5))
## Sort by increasing a and decreasing b:
dat2 <- dat[order(dat$a, dat$b, decreasing = c(FALSE, TRUE), method = "radix"),]
head(dat2)
a b
15 a pear
6 a apple
18 a apple
19 b pear
1 b orange
17 b orange
Alternatively you could sort both columns in increasing order and just reverse column b
using the function rev
:
dat3 <- dat[order(dat$a, rev(dat$b)),]
head(dat3)
a b
15 a pear
6 a apple
18 a apple
19 b pear
1 b orange
17 b orange

ikop
- 1,760
- 1
- 12
- 24
-
I just found this method is not working. Just your sample's column b is not ordered decreasing. – raccoonjin Apr 13 '17 at 07:29
-
The sorting gives priority to column a. For duplicate values of a, column b is sorted in a decreasing order. You cannot generally sort a data frame so that two columns are in a specified order. – ikop Apr 13 '17 at 08:06
0
You can arrange rows by variables easily with dplyr::arrange
Example:
set.seed(123)
dat <- data.frame(a= letters[sample(1:26, 20)],
b = rep(c("orange", "apple", "pear", "banana"), 5))
dat %>% arrange(a, desc(b))

Adam Quek
- 6,973
- 1
- 17
- 23
-
-
Check this instead... http://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns – Adam Quek Apr 13 '17 at 05:14