sort.data.frame

I came accross this post on SO, where several solutions to sorting data.frames are presented. It must have been solved a million times, but here's a solution I like to use. It benefits from the fact that sort is an S3 generic.

sort.data.frame <- function(x, decreasing=FALSE, by=1, ... ){
  f <- function(...) order(...,decreasing=decreasing)
  i <- do.call(f,x[by])
  x[i,,drop=FALSE]
}

It sorts on the first column by default, but you may use any vector of valid column indices. Here are some examples.

sort(iris, by="Sepal.Length")
sort(iris, by=c("Species","Sepal.Length"))
sort(iris, by=1:2)
sort(iris, by="Sepal.Length",decreasing=TRUE)
This entry was posted in data manipulation, R. Bookmark the permalink.

5 Responses to sort.data.frame

  1. anthony damico says:

    very cool

  2. Jeff Breiwick says:

    How about the ability to sort different columns descending or ascending?

  3. Agaz Hussain says:

    This function is quite pretty. I want to know which sorting algorithm is used in this function. How to write a function a function to insert into a sorted data frame.

    • mark says:

      R uses an implementation of quicksort, see ?sort.

      Regarding insertion, a data.frame is not a database-like object. You can only append two compatible data.frames with rbind(). If you need a lot of such operations,
      have a look at the data.table package, or check out RSQLite.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*