8
votes

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)),] 
2
Please note that CustomData[do.call(order, as.list(CustomData)),] sorts the whole dataframe using columns other than the first one only to break ties, which is a different problem than what you state - you want to sort the columns independently. - Ferdinand.kraft
It seems like one of R's map or apply routines would help for mapping sort over the columns. - Paul

2 Answers

15
votes
CD.sorted <- apply(CustomData, 2, sort, decreasing=F)
#2 == column, 1 == row 
4
votes

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