You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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")]

运行后得到的结果如下:

playermax_col
Apoints
Bpoints
Cassists
Dpoints
Erebounds
Fpoints
Grebounds

方法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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 09:06:24