Emily
Emily

Reputation: 105

Ranking in R based on multiple criteria

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.

Upvotes: 1

Views: 1642

Answers (1)

a--on-
a--on-

Reputation: 153

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)

Upvotes: 1

Related Questions