20

I've looked and looked and the answer either does not work for me, or it's far too complex and unnecessary.

I have data, it can be any data, here is an example

chickens <- read.table(textConnection("
feathers beaks
2   3
6   4
1   5
2   4
4   5
10  11                               
9   8
12  11
7   9
1   4
5   9
"), header = TRUE)

I need to, very simply, sort the data for the 1st column in descending order. It's pretty straightforward, but I have found two things below that both do not work and give me an error which says:

"Error in order(var) : Object 'var' not found.

They are:

chickens <- chickens[order(-feathers),]

and

chickens <- chickens[sort(-feathers),]

I'm not sure what I'm not doing, I can get it to work if I put the df name in front of the varname, but that won't work if I put an minus sign in front of the varname to imply descending sort.

I'd like to do this as simply as possible, i.e. no boolean logic variables, nothing like that. Something akin to SPSS's

SORT BY varname (D)

The answer is probably right in front of me, I apologize for the basic question.

Thank you!

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
Adam_S
  • 687
  • 2
  • 12
  • 24
  • I should be a good sport and mention that this is duplicate to so many things, including 10k+ reputation answers like https://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r/6871968#6871968 – dmi3kno Jul 24 '18 at 15:25
  • Take the whiz if you like, but the answers in the link are not a simple, clean, single line. And the first one, the square brackets, the with, the negative in front of the varname. I wanted to avoid all of that. Thank you for the answer below. – Adam_S Jul 24 '18 at 17:18

2 Answers2

36

You need to use dataframe name as prefix

chickens[order(chickens$feathers),]  

To change the order, the function has decreasing argument

chickens[order(chickens$feathers, decreasing = TRUE),]  
dmi3kno
  • 2,943
  • 17
  • 31
  • 1
    ...or wrap the whole expression in `with()`, or use any of the other methods for referring to a column of a data frame via `[` or `[[`. – joran Jul 24 '18 at 15:13
  • Or instead of `decreasing`, you can just put a `-` sign in front: `chickens[order(-chickens$feathers),] ` – NicolasElPapu Apr 10 '21 at 22:01
4

The syntax in base R, needs to use dataframe name as a prefix as @dmi3kno has shown. Or you can also use with to avoid using dataframe name and $ all the time as mentioned by @joran.

However, you can also do this with data.table :

library(data.table)
setDT(chickens)[order(-feathers)]
#Also
#setDT(chickens)[order(feathers, decreasing = TRUE)]

#    feathers beaks
# 1:       12    11
# 2:       10    11
# 3:        9     8
# 4:        7     9
# 5:        6     4
# 6:        5     9
# 7:        4     5
# 8:        2     3
# 9:        2     4
#10:        1     5
#11:        1     4

and dplyr :

library(dplyr)
chickens %>% arrange(desc(feathers))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213