Adam_S
Adam_S

Reputation: 770

How to sort data by column in descending order in R

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!

Upvotes: 24

Views: 86299

Answers (3)

Edward
Edward

Reputation: 19459

From R version 4.4.0, you can now use sort_by, which simplifies the sorting of data frames.

sort_by(chickens, ~feathers)

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

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389265

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))

Upvotes: 6

dmi3kno
dmi3kno

Reputation: 3055

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),]  

Upvotes: 40

Related Questions