tags:

views:

86

answers:

2

Hello and Happy Ho Ho,

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

TIA!

+1  A: 

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.

Shane
+2  A: 

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
Ian Fellows
Thanks Ian, now how would I do it if I needed to base it on the fact that the text column just had "09" in it rather than a space (I simplified my example but really a,b,c,d are company names with spaces and other characters).
Brandon Bertelsen
grep("09",text) should point you in the right direction.
Ian Fellows
I'm having a bit of difficulty putting this together. grep("09",text) is only returning a vector. Could you provide an example?
Brandon Bertelsen