如何从12个不同的列中提取前三个值并返回关联的行名称?

时间:2016-09-14 01:37:38

标签: r dataset

我正在使用内置于R中的43x12数据集.43行是不同的人名,12列是不同的统计数据。我需要得到每个统计数据在前3名中得分的人名。我几乎可以做到这一点,除非两个人对于一个统计数据具有完全相同的值,我需要通过使用另一个统计数据打破平局,我不知道该怎么做。此外,如果它们具有相同的stat值,则我的当前方法不起作用。我正在使用的内置数据集是USJudgeRatings。这是我如何获得CONT的前三名,这很好,但类似的方法对INTG不起作用,因为两个人具有相同的统计数据,这是该类别的第二高。

sortedCont <- sort(USJudgeRatings$CONT, decreasing = TRUE)
ContFilter1 <- USJudgeRatings$CONT == sortedCont[1]
ContFilter2 <- USJudgeRatings$CONT == sortedCont[2]
ContFilter3 <- USJudgeRatings$CONT == sortedCont[3]
BestJudges[1,1] <- rownames(USJudgeRatings[ContFilter1,])
BestJudges[1,2] <- rownames(USJudgeRatings[ContFilter2,])
BestJudges[1,3] <- rownames(USJudgeRatings[ContFilter3,])

1 个答案:

答案 0 :(得分:2)

您可以使用head获取顶行,例如:

row.names(head(USJudgeRatings[order(USJudgeRatings$CONT,decreasing =T),],3))
[1] "CALLAHAN,R.J." "LEVISTER,R.L." "WALL,R.A."  

然后,您可以使用sapply将其应用于每列:

sapply(USJudgeRatings, function(col) 
       row.names(head(USJudgeRatings[order(col,decreasing =T),],3)))

     CONT            INTG              DMNR            DILG           CFMG            DECI           PREP          
[1,] "CALLAHAN,R.J." "RUBINOW,J.E."    "RUBINOW,J.E."  "RUBINOW,J.E." "NARUK,H.J."    "NARUK,H.J."   "RUBINOW,J.E."
[2,] "LEVISTER,R.L." "CALLAHAN,R.J."   "CALLAHAN,R.J." "NARUK,H.J."   "DALY,J.J."     "RUBINOW,J.E." "NARUK,H.J."  
[3,] "WALL,R.A."     "O'SULLIVAN,T.J." "DALY,J.J."     "BERDON,R.I."  "CALLAHAN,R.J." "BERDON,R.I."  "BERDON,R.I." 
     FAMI           ORAL            WRIT           PHYS            RTEN           
[1,] "RUBINOW,J.E." "RUBINOW,J.E."  "RUBINOW,J.E." "CALLAHAN,R.J." "RUBINOW,J.E." 
[2,] "NARUK,H.J."   "NARUK,H.J."    "NARUK,H.J."   "NARUK,H.J."    "CALLAHAN,R.J."
[3,] "BERDON,R.I."  "CALLAHAN,R.J." "BERDON,R.I."  "RUBINOW,J.E."  "NARUK,H.J."