You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

输出结果

运行后会直接生成你需要的目标表格:

LocationSpeciesFirst DateLast DateMax CountDate with Max Count
Location1Species101-01-202401-03-2024401-02-2024
Location1Species201-01-202401-03-2024601-01-2024

关键逻辑说明

  • group_by(Location, Species):按地点和物种分组,确保每组独立计算统计值
  • min(Date)/max(Date):直接提取每组的最早、最晚日期
  • max(Count):获取每组的最大计数
  • Date[which.max(Count)]:定位计数最大值对应的日期(若多日期计数相同,返回第一个出现的日期)
  • .groups = "drop":汇总后取消分组,得到整洁的结果结构

内容的提问来源于stack exchange,提问作者basto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 17:29:59