获取与dplyr的across中另一列最大值关联的列值

k4ymrczo  于 2023-01-22  发布在  其他
关注(0)|答案(3)|浏览(117)

在按物种分组并取每组的最大萼片长度(第1列)后,我需要获取与第1列(按组)的最大值相关的第2列至第4列的值。我可以一次为每一列这样做,但不能在across过程中。有什么提示吗?

library(dplyr)
library(datasets)
data(iris)

按物种总结与最大萼片长度相关的数据(按组),逐列:

iris_summary <- iris %>%
  group_by(Species) %>%
  summarise(
    max_sep_length = max(Sepal.Length),
    sep_w_associated_to = Sepal.Width[which.max(Sepal.Length)],
    pet_l_associated_to = Petal.Length[which.max(Sepal.Length)],
    pet_w_associated_to = Petal.Width[which.max(Sepal.Length)]
  )

现在,我希望使用across获得相同的结果,但结果与我预期的不同(dfiris_summary的行数与iris相同,我不明白为什么...)

iris_summary <- iris %>%
  group_by(Species) %>%
  summarise(
    max_sepa_length = max(Sepal.Length),
    across(
      .cols = Sepal.Width : Petal.Width,
      .funs = ~ .x[which.max(Sepal.Length)]
    )
  )
gajydyqb

gajydyqb1#

或者使用slice_max

library(dplyr) # devel can have `.by` or use `group_by(Species)`
iris %>% 
   slice_max(Sepal.Length, n = 1, by = 'Species')
Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          5.8         4.0          1.2         0.2     setosa
2          7.0         3.2          4.7         1.4 versicolor
3          7.9         3.8          6.4         2.0  virginica
kq0g1dla

kq0g1dla2#

在Base R中,您可以执行以下操作:

merge(aggregate(Sepal.Length~Species, iris, max), iris)

     Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1     setosa          5.8         4.0          1.2         0.2
2 versicolor          7.0         3.2          4.7         1.4
3  virginica          7.9         3.8          6.4         2.0
gab6jxml

gab6jxml3#

如果我们想对across做同样的处理,这里有一个选项:

iris %>% 
  group_by(Species) %>% 
  summarise(across(everything(), ~ .[which.max(Sepal.Length)]))
Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
1 setosa              5.8         4            1.2         0.2
2 versicolor          7           3.2          4.7         1.4
3 virginica           7.9         3.8          6.4         2

相关问题