Re: [R] sort

From: Alfons Sutter <>
Date: Wed, 19 Mar 2008 02:58:17 -0700 (PDT)

I found the following function which solves the problem! lsort <- function(data, by = 1:dim(data)[2], asc = rep(T, length(by)), na.last = T){
# this function works like the SAS SORT procedure
# data: a dataframe or a matrix, "dimnames" are used as the variable names
# by: a vector or a list of variable names or column indices specifying
# the "sort by" variables, the default is to sort by all variables
# in the order they appear in the data set
# asc: a vector with the same length as "by" indicating whether the sorting
# of each "by" variable is in ascending order, the default order is
# ascending
# na.last: a flag indicating whether missing values are placed as the last
# elements in the data set, the default is T
# example:
# 1. sort "mydata" by "id" (ascending) and "group" (descending)
# newdata <- lsort(mydata, by=c("id","group"), asc=c(T,F))
# 2. sort "mydata" by the third and the first variable (ascending)
# newdata <- lsort(mydata, by=c(3,1))
# 3. sort "mydata" by "id" and the 7th variable (ascending)
# newdata <- lsort(mydata, by=list("id",7))

        m <- dim(data)[1]
        keys <- 1:m
        rotate <- m:1
        for(i in length(by):1) {
                        keys[] <- keys[sort.list(data[, by[[i]]][keys],na.last= na.last)]
                else keys[] <- keys[order(data[, by[[i]]][keys], rotate,
                                na.last = na.last)[rotate]]
        data[keys,  ]


TheData1 <- lsort(TheData, by=c(x1,x2))


Is there any function in R which sorted data as  

x1 <- c(1,3,2,4,5,1)
x2 <- c(2,0,2,3,5,2)
TheData <- data.frame(x1,x2)
TheData1 <- sort(TheData, by=c(x1,x2))  

Thanks in advance!

Never miss a thing. Make Yahoo your homepage.

Be a better friend, newshound, and

        [[alternative HTML version deleted]] mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Wed 19 Mar 2008 - 10:01:10 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 19 Mar 2008 - 10:30:23 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive