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

R语言实现跨年度重叠季节分组的月度气象数据求和

实现方法

核心逻辑是给跨年度的月份重新匹配统计归属年份,再通过分组行数校验剔除缺测的季节记录,完整可运行代码如下:

library(dplyr)
# 构造测试数据
set.seed(123)
dat <- 
  data.frame(Year = rep(1980:1985, each = 12),
             Month = rep(1:12, times = 6),
             value = runif(12*6))
# 季节定义
s1 <- c(11, 12, 1, 2) # 跨年度季节1
s2 <- c(3, 4, 5) # 季节2
s3 <- c(6, 7, 8, 9, 10) # 季节3

season_list <- list(s1, s2, s3)
temp_list <- list()          
for(s in seq_along(season_list)){
  
  season_ref <- unlist(season_list[s])
  
  if(sum(diff(season_ref) < 0) != 0){  # 跨年度季节处理
    temp_list[[s]] <- dat %>% 
      dplyr::filter(Month %in% season_ref) %>%
      # 生成统计归属年份:11、12月归属到下一年的统计年度
      dplyr::mutate(Year = ifelse(Month >= 11, Year + 1, Year)) %>%
      dplyr::group_by(Year) %>%
      dplyr::summarise(
        season_value = sum(value),
        month_count = n()
      ) %>%
      # 剔除月份不全的季节记录
      dplyr::filter(month_count == length(season_ref)) %>%
      dplyr::select(-month_count) %>%
      dplyr::mutate(season = s)
  } else {  # 非跨年度季节处理
    temp_list[[s]] <- 
      dat %>% 
      dplyr::filter(Month %in% season_ref) %>%
      dplyr::group_by(Year) %>%
      dplyr::summarise(season_value = sum(value)) %>%
      dplyr::mutate(season = s)
  }
}
# 合并所有季节结果
final_res <- dplyr::bind_rows(temp_list)

结果说明

最终输出的final_res共17条记录:

  • 季节1(s1):1981-1985年共5条,自动剔除了缺1979年11-12月的1980年记录、以及归属1986年的1985年11-12月记录
  • 季节2(s2)、季节3(s3):各包含1980-1985年共6条记录
    所有记录均已按要求完成季节内月度值求和。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:36:04