在 R 中按组提取最小值/最大值 [英] Extract min/max by group in R

查看:66
本文介绍了在 R 中按组提取最小值/最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(使用 Iris 实现可重复性)

(Using Iris for reproducibility)

我想通过 Petal.Width & 计算最小/最大行按 R 中的 Species 分组.我已经使用两种方法完成了该操作,我想了解是否有更好的方法(最好是 tidyverse),还请注意,由于关系的原因,两者的答案可能会有所不同.以上两种方式如有不对之处请指正.

I want to calculate min/max row by Petal.Width & grouped by Species in R. I have done that using two approaches, I want to understand is there a better approach (preferably tidyverse) , also note because of ties answer might vary in both. Please correct if there is anything wrong in both these approaches.

方法一

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()))

推荐答案

你也可以像下面这样使用 slice :

You could also use slice like below:

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 

这篇关于在 R 中按组提取最小值/最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆