如何在R语言数据框中获取每行最大值对应的列名?
解决方案
方法1:基础R实现
使用apply按行遍历目标列,通过which.max定位最大值位置,匹配对应列名:
# 原数据框创建代码 df <- data.frame(player=c('A', 'B', 'C', 'D', 'E', 'F', 'G'), points=c(28, 17, 3, 14, 3, 26, 5), rebounds=c(5, 6, 4, 7, 14, 12, 9), assists=c(10, 13, 7, 8, 4, 5, 8)) # 保留原最大值列 df$max_points_rebs <- pmax(df$points, df$rebounds, df$assists) # 新增最大值对应的列名列 df$max_col <- apply(df[, c("points", "rebounds", "assists")], 1, function(x) { names(x)[which.max(x)] }) # 提取你需要的结果列 df[, c("player", "max_col")]
运行后得到的结果如下:
| player | max_col |
|---|---|
| A | points |
| B | points |
| C | assists |
| D | points |
| E | rebounds |
| F | points |
| G | rebounds |
方法2:tidyverse 风格实现
如果习惯使用tidyverse工具链,可通过rowwise()结合which.max实现:
library(dplyr) df <- df %>% rowwise() %>% mutate(max_col = names(which.max(c(points, rebounds, assists)))) %>% ungroup() # 查看目标结果 select(df, player, max_col)
注意:如果存在多列数值相同且均为最大值的情况,上述两种方法都会返回第一个出现的列名,若需要处理多最大值场景,可根据需求调整逻辑。
内容的提问来源于stack exchange,提问作者Miquel Vallbona
相关产品推荐
相关产品推荐

