Adding a ranking column to the data framework

This seems like a very common task, but I can't find a solution in google or SO. I want to add the "rank" column to "dat1" based on the sequence that "order.scores" refers to "dat". I tried using row.names (), but the growth names are based on 'dat', not 'dat1'. I also tried 'dat $ rank <-rank (dat1)', but this causes an error message.

fname<-c("Joe", "Bob", "Bill", "Tom", "Sue","Sam","Jane","Ruby")
score<-c(500, 490, 500, 750, 550, 500, 210, 320)
dat<-data.frame(fname,score)
order.scores<-order(dat$score,dat$fname)
dat1<-dat[order.scores,]
+4
source share
4 answers

You can calculate the ranking from the order as follows:

dat$rank <- NA
dat$rank[order.scores] <- 1:nrow(dat)
dat
#   fname score rank
# 1   Joe   500    5
# 2   Bob   490    3
# 3  Bill   500    4
# 4   Tom   750    8
# 5   Sue   550    7
# 6   Sam   500    6
# 7  Jane   210    1
# 8  Ruby   320    2
+4
source

Try:

## dat, dat1, and order.scores as defined
dat <- data.frame(fname=c("Joe", "Bob", "Bill", "Tom", "Sue","Sam","Jane","Ruby"),
                  score=c(500, 490, 500, 750, 550, 500, 210, 320))
order.scores <- order(dat$score)
dat1 <- dat[order.scores,]
dat1$rank <- rank(dat1$score)
dat1
##    fname score rank
##  7  Jane   210    1
##  8  Ruby   320    2
##  2   Bob   490    3
##  3  Bill   500    5
##  1   Joe   500    5
##  6   Sam   500    5
##  5   Sue   550    7
##  4   Tom   750    8

$score. $rank, dat1$rank <- 1:nrow(dat1), .

+3

:

 dat$rank <- order(order.scores)
  dat$rank
 #[1] 5 3 4 8 7 6 1 2
0

You can use:

dat$Rank <-  rank(dat$score)
dat$Rank
0
source

All Articles