简体   繁体   English

在 R 中识别数据帧中具有最高数值的列

[英]Identifying Column With Highest Numeric Value in Data Frame in R

I've got a data frame with a large number of columns.我有一个包含大量列的数据框。 Each is numeric.每个都是数字。

For each row of data I'd like to know which column has the highest number in it.对于每一行数据,我想知道哪一列的数字最高。

Very simple example:非常简单的例子:

x <- data.frame(score1 = c(10, 12, 25),
                score2 = c(9, 13, 20),
                score3 = c(14, 8, 8))

For row 1, score3 is highest.对于第 1 行,分数 3 最高。

For row 2, score2 is highest.对于第 2 行,score2 最高。

For row 3, score1 is highest.对于第 3 行,score1 最高。

So I'd like something that outputs:所以我想要输出的东西:

max_score_col_name <- c("score3", "score2", "score1")

Is there an easy way to do this please?请问有没有简单的方法可以做到这一点?

(I've ignored the tricky question of what happens if there's a tie for the lead because the data is in a form such that this won't happen) (我忽略了一个棘手的问题,即如果领先者有平局会发生什么,因为数据的形式不会发生这种情况)

One option could be:一种选择可能是:

names(x)[max.col(x)]

[1] "score3" "score2" "score1"

另外一个选项:

colnames(x)[apply(x, 1, which.max)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM