使用来自不同列的 dplyr 和 return 元素在列中查找最大值

Finding max values in columns using dplyr and return element from different column

假设以下数据框:

df<-data.frame(a=c("red", "blue", "yellow", "orange"), b=c(1,4,5,7), c=c(2,7,4,1), d=c(4,3,8,1))

使用dplyr,我想获得对应于列b,cd中每个最大值和最小值的a元素:

对于最大值,这将 return orange, blue and yellow

我能够获取 max 值的索引,但无法从列 a:

中获取值

df %>% summarise(across(-c(1), ~which.max(.x)))

试试这个。将数据重塑为 long,然后按包含列的 name 变量分组。在该过滤器之后获取最大值并识别 a 变量中的观察值。这里的代码:

library(tidyverse)
#Code
newdf <- df %>% pivot_longer(-a) %>% group_by(name) %>% filter(value==max(value))

输出:

# A tibble: 3 x 3
# Groups:   name [3]
  a      name  value
  <fct>  <chr> <dbl>
1 blue   c         7
2 yellow d         8
3 orange b         7

整形为'long'格式后我们可以使用slice_max

library(dplyr)
library(tidyr)
df %>% 
    pivot_longer(-a) %>% 
    group_by(name) %>% 
    slice_max(value)

-输出

# A tibble: 3 x 3
# Groups:   name [3]
#  a      name  value
#  <chr>  <chr> <dbl>
#1 orange b         7
#2 blue   c         7
#3 yellow d         8