# Re: [R] sort

From: Alfons Sutter <alfonssutter_at_yahoo.com>
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) {
if(asc[i])
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))

• Original Message ---- From: Alfons Sutter <alfonssutter_at_yahoo.com> To: r-help_at_stat.math.ethz.ch Sent: Wednesday, March 19, 2008 10:41:26 AM Subject: sort

Hello,

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

Never miss a thing. Make Yahoo your homepage.

Be a better friend, newshound, and

[[alternative HTML version deleted]]

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html 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 https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.