如何在R的tibble中统计满足多条件的水果种类数量
解决思路与代码实现
1. 构造示例测试数据
library(tibble) library(dplyr) # 模拟题目中的数据集 fruit_data <- tibble( year = c(2001, 2001, 2002, 2002, 2003, 2003), fruit = c("Apple", "Ananas", "Apple", "Ananas", "Apple", "Banana"), n = c(2001, 50, 40, 60, 55, 70) )
2. 核心统计逻辑
假设我们要统计:有多少种水果,在至少2个年份里食用次数n超过50(可根据需求调整阈值和目标年份数)
# 自定义参数,按需修改 threshold <- 50 # 食用次数阈值 target_year_count <- 2 # 要求满足条件的最少年份数 # 统计符合条件的水果数量 qualified_fruit_count <- fruit_data %>% group_by(fruit) %>% # 统计每个水果满足n>阈值的年份数量 summarise(qualified_year_num = sum(n > threshold, na.rm = TRUE)) %>% # 筛选出达到目标年份数的水果 filter(qualified_year_num >= target_year_count) %>% # 计数最终符合条件的水果种类 nrow() # 查看结果 qualified_fruit_count
3. 细节调整说明
- 如果需求是「食用次数大于等于阈值」,把
n > threshold改成n >= threshold即可 - 如果要求「刚好等于特定年份数」,将
>=替换为== - 如果想查看每个水果对应的合格年份数,去掉最后一步的
nrow(),就能得到每个水果的统计明细 - 若数据存在缺失值,
na.rm = TRUE会自动忽略缺失的n值,避免统计出错
4. 简洁写法
也可以用更紧凑的逻辑完成统计:
qualified_fruit_count <- fruit_data %>% group_by(fruit) %>% filter(n > threshold) %>% count() %>% filter(n >= target_year_count) %>% nrow()
内容的提问来源于stack exchange,提问作者8905t
相关产品推荐
相关产品推荐

