I am working in R would like some help on ranking with multiple criteria. Using the mtcars
dataset - I want to generate a new column in this case based initially on the rank of mtcars$mpg
, then in the case of ties for this to be decided by the rank of mtcars$qsec for example. I have mtcars["rank"] = NA
then mtcars$rank=rank(mtcars$mpg)
but not sure how to include how to deal with the ties. I've tried mtcars$rank=order(mtcars$mpg, mtcars$qsec)
but not getting the outcome I want - I want the initial ranking for mtcars$mpg
and in the event of ties for this to be decided by the lower ranking in mtcars$qsec
. Thanks.
Asked
Active
Viewed 1,459 times
1

Emily
- 93
- 1
- 6
-
1Welcome to SO! Please provide a [minimal](http://stackoverflow.com/help/mcve) and [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) question, including sample data and code attempted. If you don't want to use your own data, consider a similar problem with a pre-installed dataset such as `mtcars` or `iris` (to name but two). – r2evans Jul 06 '16 at 18:29
-
Thanks - sorry I'm new to R and SO. Easier to use the mtcars dataset - I want to generate a new dataset or say column in this case based initially on the rank of `mtcars$mpg`, then in the case of ties for this to be decided by the rank of `mtcars$qsec` for example. I have `mtcars[rank] = NA` then `mtcars$rank=rank(mtcars$mpg)` but not sure how to include how to deal with the ties. – Emily Jul 06 '16 at 18:45
-
Additionally, `order(...)` allows multiple levels, so `order(mtcars$mpg, mtcars$qsec)` does what you (I?) think it should. – r2evans Jul 06 '16 at 18:50
-
1I don't see in the help how to break the ties based on the value of another column? – Emily Jul 06 '16 at 18:55
-
@Emily please edit your question and add details provided in the comments. Thanks – ahajib Jul 06 '16 at 18:56
-
Thanks updated the question now. – Emily Jul 06 '16 at 19:27
-
Does `mtcars$mpgrnk[order(mtcars$mpg, mtcars$qsec)] <- 1:nrow(mtcars)` work? – r2evans Jul 06 '16 at 20:08
-
Yes, that seems to have done it! Just getting my head around differences between rank and order... Thanks! – Emily Jul 06 '16 at 20:32
1 Answers
1
I would first order
it based on mpg
and qsec
.
mtcars <- mtcars[order(mtcars$mpg, mtcars$qsec), ]
Ranking is now simply giving indexing to the dataframe.
mtcars$rank <- 1:nrow(mtcars)

AntonySamuelB
- 143
- 7