[英]Extract min/max by group in R
(使用 Iris 實現可重復性)
我想通過 Petal.Width 和 R 中的物種分組來計算最小/最大行。我已經使用兩種方法完成了這一點,我想了解是否有更好的方法(最好是 tidyverse),還請注意,由於關系答案可能會有所不同兩個都。 如果這兩種方法有任何錯誤,請更正。
方法一
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))
方法二
iris %>%
group_by(Species) %>%
arrange(Petal.Width) %>%
filter(row_number() %in% c(1,n()))
這是使用summarise(across())
:
library(dplyr)
iris %>%
group_by(Species) %>%
summarise(across(.cols = Petal.Width,
.fns = list(min = min, max = max),
.names = "{col}_{fn}"))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 3
Species Petal.Width_min Petal.Width_max
<fct> <dbl> <dbl>
1 setosa 0.1 0.6
2 versicolor 1 1.8
3 virginica 1.4 2.5
您可以通過以下方式輕松找到數據集中每個數值變量的最小值和最大值:
iris %>%
group_by(Species) %>%
summarise(across(where(is.numeric),
.fns = list(min = min, max = max),
.names = "{col}_{fn}"))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 9
Species Sepal.Length_min Sepal.Length_max Sepal.Width_min Sepal.Width_max Petal.Length_min Petal.Length_max Petal.Width_min Petal.Width_max
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 setosa 4.3 5.8 2.3 4.4 1 1.9 0.1 0.6
2 versicolor 4.9 7 2 3.4 3 5.1 1 1.8
3 virginica 4.9 7.9 2.2 3.8 4.5 6.9 1.4 2.5
使用aggregate
。
aggregate(Petal.Width ~ Species, iris, function(x) c(min=min(x), max=max(x)))
# Species Petal.Width.min Petal.Width.max
# 1 setosa 0.1 0.6
# 2 versicolor 1.0 1.8
# 3 virginica 1.4 2.5
您還可以使用如下slice
:
iris %>%
group_by(Species) %>%
slice(which.min(Petal.Width),
which.max(Petal.Width))
輸出:
# A tibble: 6 x 5
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5 3.5 1.6 0.6 setosa
2 5.9 3.2 4.8 1.8 versicolor
3 6.3 3.3 6 2.5 virginica
4 4.9 3.1 1.5 0.1 setosa
5 4.9 2.4 3.3 1 versicolor
6 6.1 2.6 5.6 1.4 virginica
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.