11

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)),] 
Maximilian
  • 4,177
  • 7
  • 46
  • 85
  • possible duplicate of [How to sort a dataframe by column(s) in R](http://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r) – Metrics Aug 20 '13 at 17:39
  • 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 Aug 20 '13 at 18:05
  • It seems like one of R's map or apply routines would help for mapping sort over the columns. – Paul Aug 21 '13 at 02:17

2 Answers2

17
CD.sorted <- apply(CustomData, 2, sort, decreasing=F)
#2 == column, 1 == row 
chupvl
  • 1,258
  • 2
  • 12
  • 20
7

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))),]
user2332849
  • 1,421
  • 1
  • 9
  • 12