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

按地块ID在测量周期内累积月降水量的R语言实现求助

按地块ID累积指定时间段降水量的解决方案

问题描述

需要按地块ID,结合每个地块的测量起止日期,累积对应时间段内的月降水量,但现有代码未匹配地块ID,导致计算结果不符合需求。

数据定义

require(dplyr)
require(lubridate)

# 降水量数据:按地块ID、日期存储月降水量
precip <- as.data.frame(cbind(id=c(1,1,1,1), date_met=c('2021-01-01', '2021-02-01', '2021-03-01', '2021-04-01'), precip=c(20, 23, 23, 23))) %>%
  mutate(precip=as.numeric(precip), date_met=ymd(date_met))

# 测量数据:按地块ID存储每个测量周期的起止日期
meas <- as.data.frame(cbind(id=c(1,1,2), ini_date=c('2021-01-01', '2022-02-02', '2021-02-03'), fin_date=c('2022-02-02','2023-04-03','2022-02-03'))) %>%
  mutate(ini_date=ymd(ini_date), fin_date=ymd(fin_date))

现有代码问题

原代码调用cumulative时直接使用整个precip数据集,未筛选对应地块ID的降水数据,导致所有地块的计算都包含了全部降水记录,无法实现按地块单独累积的需求。

修正后的代码

require(cropgrowdays)
require(purrr)

yield <- meas %>%
  mutate(swd = pmap_dbl(list(id, ini_date, fin_date), function(plot_id, start, end) {
    # 筛选当前地块的降水数据
    plot_precip <- precip %>% filter(id == plot_id)
    # 计算该地块指定时间段的累积降水量
    cumulative(plot_precip, var = precip, startdate = start, enddate = end)
  }))

代码说明

  • 使用pmap_dbl同时传递id、ini_date、fin_date三个参数,确保每行测量数据都能匹配对应地块的降水记录
  • 在匿名函数中先通过filter(id == plot_id)筛选当前地块的降水数据,再调用cumulative计算该地块在指定时间段内的累积降水量
  • 若某地块无对应降水数据(如示例中的地块2),cumulative会返回0(根据cropgrowdays包的函数逻辑)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:12:53