Calculate rank with ties based on more than one variable

前端 未结 2 744
星月不相逢
星月不相逢 2020-12-21 17:14

I\'m trying to compute a medal table for a sports event.

My data looks like this:

test <- data.frame(\"ID\" = c(\"1_1\", \"1_2\", \"1_3\", \"1_4\         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 18:00

    You may use the data.table equivalent of base::rank, frank. A nice feature with frank is that it accepts, not only vectors (as in rank), but also a data.frame or a data.table as input. For these types of objects, the rank may be based on several columns.

    Using your original data.frame:

    test$rank <- data.table::frank(test, -gold, -silver, -bronze, ties.method = "min")
    

    Or if you want to go all in with data.table functions:

    setDT(test)[ , rank := frank(test, -gold, -silver, -bronze, ties.method = "min")]
    setorder(test, rank)
    

提交回复
热议问题