Brandon Bertelsen
Brandon Bertelsen

Reputation: 44658

Inner sort with R - Once by numeric then by alpha

I have a data.frame, like this:

nums<-c(5,7,8,9,10,3,2,1)
text<-c("a","b","c","d","a 09","b 09","c 09","d 09")
this <- data.frame()
this <- cbind(text,nums)

"a"   5 
"b"   7
"c"   8
"d"   9
"a 09" 10
"b 09" 3
"c 09" 2
"d 09" 1

a:d = data from 2010, a 09:d:09 = data from 2009. I'd like it to be sorted first by the numeric column from greatest to least and then by the string column. The only catch is that the string column has to show the 09' data underneath the 2010 data, like this:

"d"   9
"d 09" 1
"c"   8
"c 09" 2
"b"   7
"b 09" 3
"a"   5 
"a 09" 10

Upvotes: 0

Views: 306

Answers (2)

Ian Fellows
Ian Fellows

Reputation: 17348

The Deducer package has a nice sorting function for data.frames:

> library(Deducer)
> text<-c("a","b","c","d","a 09","b 09","c 09","d 09")
> nums<-c(5,7,8,9,10,3,2,1)
> t1<-sapply(text,function(x) strsplit(x," ")[[1]][1])
> t2<-sapply(text,function(x) strsplit(x," ")[[1]][2])
> dat<-data.frame(text,nums,t1,t2)
> sort(dat,by=~-t1 -t2)
     text nums t1   t2
d       d    9  d <NA>
d 09 d 09    1  d   09
c       c    8  c <NA>
c 09 c 09    2  c   09
b       b    7  b <NA>
b 09 b 09    3  b   09
a       a    5  a <NA>
a 09 a 09   10  a   09

Upvotes: 2

Shane
Shane

Reputation: 100164

One suggestion:

Try running order() on the first column, and then swap every two rows by creating an index on the odd and even indexes separately, and assigning them respectively to a new vector.

Upvotes: 1

Related Questions