如何在R中按Size分组统计各Spring_type的数量?
解决方案
1. 统计每个尺寸下弹簧类型的数量
用dplyr包的分组统计功能,按Size和Spring_type双重分组后计算每组数量,就能得到你想要的统计表格:
示例代码(R语言)
library(dplyr) # 构造你的数据 bed_data <- tibble( Size = c("Q", "K", "K", "Q", "T", "S", "T"), Spring_type = c("firm", "soft", "soft", "medium", "soft", "medium", "firm") ) # 分组统计数量 count_result <- bed_data %>% group_by(Size, Spring_type) %>% summarize(type_total = n(), .groups = "drop") # 查看结果 count_result
输出结果(匹配你期望的格式)
| Size | Spring_type | type_total |
|---|---|---|
| Q | firm | 1 |
| Q | medium | 1 |
| K | soft | 2 |
| T | soft | 1 |
| T | firm | 1 |
| S | medium | 1 |
2. 筛选每个尺寸对应的最常见弹簧类型
如果要进一步找出每个Size下数量最多的Spring_type,可在统计结果基础上继续处理:
most_common <- count_result %>% group_by(Size) %>% slice_max(order_by = type_total, n = 1, with_ties = TRUE) # 查看结果 most_common
输出结果
| Size | Spring_type | type_total |
|---|---|---|
| Q | firm | 1 |
| Q | medium | 1 |
| K | soft | 2 |
| T | soft | 1 |
| T | firm | 1 |
| S | medium | 1 |
(注:若某个尺寸下多个弹簧类型数量并列最多,with_ties = TRUE会保留所有结果;若只想保留一个,可将参数设为FALSE)
内容的提问来源于stack exchange,提问作者Yuri Rolimus
相关产品推荐
相关产品推荐

