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

R语言按组计算数据框最新月份与上年同期数值百分比变化

方案1:按月份编码匹配(更稳妥,避免数据缺行导致结果错误)

这个方案直接利用month编码的规则(前两位为年份、后两位为月份,同比月份编码差为100)匹配同期数据,不受行顺序、缺行影响:

library(dplyr)

result <- x %>%
  group_by(retailer, store) %>%
  summarise(
    # 取最新月份
    latest_month = max(month),
    latest_dollars = dollars[month == latest_month],
    # 匹配去年同期月份
    last_year_dollars = dollars[month == latest_month - 100],
    # 计算同比变化百分比,保留2位小数,无同期数据返回NA
    YoY_pct = round((latest_dollars - last_year_dollars)/last_year_dollars * 100, 2)
  ) %>%
  ungroup()

你提供的示例数据运行后得到的同比为:最新月份2110的金额121817.9,去年同期2010的金额382675.5,计算结果为-68.17%。


方案2:按行索引取值(符合你最初的思路)

如果你的数据已经提前按月份降序排序、且确认每个分组都至少有13行完整数据,可以用这个方案:

result <- x %>%
  # 先确保按月份降序排列,保证第1行是最新月,第13行是去年同期
  arrange(retailer, store, desc(month)) %>%
  group_by(retailer, store) %>%
  summarise(
    latest_dollars = nth(dollars, 1),
    last_year_dollars = nth(dollars, 13),
    YoY_pct = round((latest_dollars - last_year_dollars)/last_year_dollars * 100, 2)
  ) %>%
  ungroup()

注意:推荐优先使用方案1,避免数据排序错误、缺漏月份导致的计算偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:39:03