0

This is my first time asking a question here, so please be patient.

I'm having an issue with using order()

This is the data frame. It has 294 observations and 46 variables.

This is the code that I'm using

i <- order(data[ , 17], data[ , 2], decreasing = FALSE)

rdata <-data[i, ]

For ease of reading, I've removed all of the variables except the two that I am ordering by. Here are the results.

What I wanted was for column 17 to be ordered from smallest to largest, and if two or more values in column 17 were the same, for those to be ordered alphabetically by column 2.

For some reason, the results aren't quite correct. Perhaps, I have too many observations or something, but instead of everything being ordered by column 17 (1:294) it's ordered by column 17 (251:294, 1:250)

Sorry, how else can I share the data?

Basically, rows 251 to 294 should be "prepended" to the beginning of the result data frame

Thank you for your help

i <- order(as.numeric(data[ , 17]), data[ , 2], decreasing = FALSE)

rdata <-data[i, ]

This works properly now.

user3752138
  • 75
  • 1
  • 7
  • 4
    Please don't share data via google drive. It asks people to log-in. I won't do that simply to see your data. – Roland Jun 18 '14 at 11:46
  • See [this topic](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to share data. Also doesn't `rdata<-data[order(data[,17],data[,2]),]` work? – horseoftheyear Jun 18 '14 at 11:52
  • 1
    You're using `order` incorrectly. Try `?order` to learn more. – rrs Jun 18 '14 at 11:59
  • Yes, what you posted works, but I get the same results. – user3752138 Jun 18 '14 at 12:00
  • 2
    what's the class of `df[,2]` (check `class(df[,2])`)? In case it's `factor` you could try `rdata<-data[order(data[,17],as.character(data[,2])),]`. Does that change anything in the resulting data.frame? – talat Jun 18 '14 at 12:01
  • Start with a nice small test matrix so you can see what's happening. Then fix your code. – Carl Witthoft Jun 18 '14 at 12:37

1 Answers1

0

If i get you right, Here is what you should be doing -

i     <- data [order(data [,17],data [,2]),]
rdata <- subset(i, select=c(i[,17],i[,2]))

Or you can use the plyr package and say -

i     <- arrange(data,data[,17],data[,2])
rdata <- subset(i, select=c(i[,17],i[,2]))
RHelp
  • 815
  • 2
  • 8
  • 23