如何删除R中包含少于3行数据的组? [英] How to delete groups containing less than 3 rows of data in R?

查看:33
本文介绍了如何删除R中包含少于3行数据的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中使用 dplyr 包,并按 3 个变量(Year、Site、Brood)对我的数据进行分组.

I'm using the dplyr package in R and have grouped my data by 3 variables (Year, Site, Brood).

我想去掉少于 3 行的组.例如,在下面的示例中,我想删除育雏2"的行.我有很多数据要处理,所以虽然我可以辛苦地手工完成,但使用 R 自动化它会很有帮助.

I want to get rid of groups made up of less than 3 rows. For example in the following sample I would like to remove the rows for brood '2'. I have a lot of data to do this with so while I could painstakingly do it by hand it would be so helpful to automate it using R.

Year Site Brood Parents
1996 A    1     1  
1996 A    1     1  
1996 A    1     0  
1996 A    1     0  
1996 A    2     1      
1996 A    2     0  
1996 A    3     1  
1996 A    3     1  
1996 A    3     1  
1996 A    3     0  
1996 A    3     1  

我希望这是有道理的,非常感谢您的帮助!我是 R 和 stackoverflow 的新手,如果我提出这个问题的方式不太好,我深表歉意!如果我需要提供任何其他信息,请告诉我.

I hope this makes sense and thank you very much in advance for your help! I'm new to R and stackoverflow so apologies if the way I've worded this question isn't very good! Let me know if I need to provide any other information.

推荐答案

一种方法是在 filter 中使用神奇的 n() 函数:

One way to do it is to use the magic n() function within filter:

library(dplyr)

my_data <- data.frame(Year=1996, Site="A", Brood=c(1,1,2,2,2))

my_data %>% 
  group_by(Year, Site, Brood) %>% 
  filter(n() >= 3)

n() 函数给出当前组中的行数(如果没有分组,则为总行数).

The n() function gives the number of rows in the current group (or the number of rows total if there is no grouping).

这篇关于如何删除R中包含少于3行数据的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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