Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort data by column in descending order in R

Tags:

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!

like image 797
Adam_S Avatar asked Jul 24 '18 15:07

Adam_S


People also ask

How do you sort a Dataframe according to a column in R?

Methods to sort a dataframe:order() function (increasing and decreasing order) arrange() function from dplyr package. setorder() function from data. table package.

How do I sort an array in descending order in R?

sort() function in R is used to sort a vector. By default, it sorts a vector in increasing order. To sort in descending order, add a “decreasing” parameter to the sort function.

How do I sort numbers in a column in R?

order() in R The numbers are ordered according to its index by using order(x) . Here the order() will sort the given numbers according to its index in the ascending order.


2 Answers

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),]  
like image 72
dmi3kno Avatar answered Sep 24 '22 00:09

dmi3kno


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))
like image 45
Ronak Shah Avatar answered Sep 24 '22 00:09

Ronak Shah