Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort descending all columns of data.frame

Tags:

r

I'm fiddling with this now for a while, but can't find reasonable solution.

I would like to sort in descending order all columns of data.frame.

Sample data for instance:

CustomData <- data.frame(Value1=rnorm(100,1,2), Value2=rnorm(100,2,3),
                         Value3=rexp(100,5), Value4=rexp(100,2))

Works for one column:

CustomData[order(CustomData$Value1, decreasing=FALSE), ]

How sort all the columns data in decreasing/increasing order in reasonable manner? Thx.

I have also tried something like this as posted elsewhere, but doesn't work as stated.

CustomData[do.call(order, as.list(CustomData)),] 
like image 503
Maximilian Avatar asked Aug 20 '13 17:08

Maximilian


People also ask

How do you sort a column in a Dataframe in descending order?

We can sort it by using the dataframe. sort_index() function. Alternatively, you can sort the index in descending order by passing in the ascending=False the argument in the function above.

How do I sort an entire data frame?

Sorting Your DataFrame on a Single Column. To sort the DataFrame based on the values in a single column, you'll use . sort_values() . By default, this will return a new DataFrame sorted in ascending order.


2 Answers

Using do.call is much faster.

For ascending order.

CustomData[do.call(order, CustomData),]

For decreasing order the syntax is a bit more elaborate because we have to pass the 'decreasing' argument.

CustomData[do.call(order, c(CustomData, list(decreasing=TRUE))),]
like image 72
user2332849 Avatar answered Oct 08 '22 16:10

user2332849


CD.sorted <- apply(CustomData, 2, sort, decreasing=F)
#2 == column, 1 == row 
like image 24
chupvl Avatar answered Oct 08 '22 17:10

chupvl