-1

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"

Joshua
  • 34,237
  • 6
  • 59
  • 120
raccoonjin
  • 207
  • 1
  • 4
  • 12

2 Answers2

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,589
  • 10
  • 23
  • 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
  • 5,660
  • 1
  • 11
  • 20