【发布时间】:2020-10-05 11:22:30
【问题描述】:
(使用 Iris 实现重现性)
我想通过 Petal.Width 计算最小/最大行并按 R 中的 Species 分组。我已经使用两种方法做到了,我想了解是否有更好的方法(最好是 tidyverse),也请注意因为关系答案两者可能有所不同。如果这两种方法有任何错误,请更正。
方法 1
library(tidyverse)
iris %>%
group_by(Species) %>%
slice_max(Petal.Width, n = 1, with_ties=FALSE) %>%
rbind(
iris %>%
group_by(Species) %>%
slice_min(Petal.Width, n = 1, with_ties=FALSE))
方法 2
iris %>%
group_by(Species) %>%
arrange(Petal.Width) %>%
filter(row_number() %in% c(1,n()))
【问题讨论】: