首页 > 解决方案 > 如何使用 dplyr 从每一行中获取最大的列值

问题描述

鉴于以下数据:

df <- data.frame(
  a = c(1,2,3,5),
  b = c(7,9,52,4),
  c = c(53, 11,22,1),
  d = c("something","string","another", "here")
)

看起来像:

  a  b  c         d
1 1  7 53 something
2 2  9 11    string
3 3 52 22   another
4 5  4  1      here

我想使用 dplyr 创建列“max”,其中max是最大行值的列。

所以对于上述我会

  a  b  c         d  max
1 1  7 53 something   c
2 2  9 11    string   c
3 3 52 22   another   b
8 5  4  1      here   a

标签: rdplyrtidyr

解决方案


我们可以使用max.col查找每行最大值的列索引,使用它来获取列名并分配 ass 'max' 列

df['max'] <- names(df)[1:3][max.col(df[1:3], "first")]
df
#  a  b  c         d max
#1 1  7 53 something   c
#2 2  9 11    string   c
#3 3 52 22   another   b
#4 5  4  1      here   a

使用tidyverse,另一种方法是重塑为“长”格式,然后找到max

library(dplyr)
library(tidyr)
df %>%
   mutate(ind = row_number()) %>%
   select(-d) %>%
   pivot_longer(cols = a:c) %>%
   group_by(ind) %>%
   slice(which.max(value)) %>%
   select(-value) %>%
   pull(name) %>%
   mutate(df, max = .)

或与pmap

library(purrr)
df %>% 
   mutate(max = pmap_chr(select(., a:c), ~ c(...) %>% 
                                   which.max %>% 
                                   names ))

推荐阅读