如何用R和dplyr简便实现指定格式的数据转换?
简便解决方案(R + dplyr)
1. 构造示例数据
先把你提供的原始数据转换成可直接运行的R对象:
library(dplyr) original_data <- tibble( Location = c("Location1", "Location1", "Location1", "Location1", "Location1"), Species = c("Species1", "Species1", "Species1", "Species2", "Species2"), Date = c("01-01-2024", "01-02-2024", "01-03-2024", "01-01-2024", "01-03-2024"), Count = c(2, 4, 3, 6, 3) )
2. 一步式分组汇总
用dplyr的分组+汇总就能直接得到目标格式,无需复杂中间步骤:
target_data <- original_data %>% group_by(Location, Species) %>% summarize( `First Date` = min(Date), `Last Date` = max(Date), `Max Count` = max(Count), `Date with Max Count` = Date[which.max(Count)], .groups = "drop" ) # 查看结果 target_data
输出结果
运行后会直接生成你需要的目标表格:
| Location | Species | First Date | Last Date | Max Count | Date with Max Count |
|---|---|---|---|---|---|
| Location1 | Species1 | 01-01-2024 | 01-03-2024 | 4 | 01-02-2024 |
| Location1 | Species2 | 01-01-2024 | 01-03-2024 | 6 | 01-01-2024 |
关键逻辑说明
group_by(Location, Species):按地点和物种分组,确保每组独立计算统计值min(Date)/max(Date):直接提取每组的最早、最晚日期max(Count):获取每组的最大计数Date[which.max(Count)]:定位计数最大值对应的日期(若多日期计数相同,返回第一个出现的日期).groups = "drop":汇总后取消分组,得到整洁的结果结构
内容的提问来源于stack exchange,提问作者basto
相关产品推荐
相关产品推荐

