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

R语言时间序列处理:基于历史增长率迭代填充counterfactual缺失值

时间序列中基于增长率迭代计算Counterfactual值的实现方法

需求说明

在时间序列分析场景中,需按以下规则计算counterfactual列的值:

  • 2020年3月及之前,counterfactual与observed_value完全一致;
  • 2020年2月之后的缺失值,通过**前一月的counterfactual值 × (1 + 当前行的growth_rate)**迭代填充。

示例数据

df <- data.frame("month" = c("Jan", "Feb", "March", "April"),
                 "year" = c(2020, 2020, 2020, 2020),
                 "observed_value" = c(15,18,22,19),
                 "growth_rate" = c(0.001, -0.549, 0.4788, -0.11),
                 "counterfactual" = c(15,18,NA,NA))

计算逻辑示例

  • 2020年3月的counterfactual值:18 × (1 + 0.4788) = 26.62
  • 2020年4月的counterfactual值:26.62 × (1 - 0.11) = 23.69

解决方案

以下提供两种R语言实现方式:

方法1:基础R循环(直观易读)

利用循环逐行迭代计算,适合数据已按时间顺序排列的场景:

# 从第3行(对应March)开始迭代计算
for (i in 3:nrow(df)) {
  df$counterfactual[i] <- df$counterfactual[i-1] * (1 + df$growth_rate[i])
}

# 保留两位小数,匹配期望输出格式
df$counterfactual <- round(df$counterfactual, 2)

方法2:Tidyverse函数式实现(简洁高效)

使用purrr包的accumulate函数实现累积迭代,适合tidyverse工作流:

library(dplyr)
library(purrr)

df <- df %>%
  mutate(
    counterfactual = accumulate(seq_along(counterfactual), function(prev_val, idx) {
      if (idx == 1) {
        counterfactual[idx]
      } else if (!is.na(counterfactual[idx])) {
        counterfactual[idx]
      } else {
        prev_val * (1 + growth_rate[idx])
      }
    }, .init = counterfactual[1]) %>% 
      tail(-1) %>%  # 移除初始值
      round(2)
  )

最终输出

运行上述代码后,得到与期望一致的结果:

# 输出结果
df
#   month year observed_value growth_rate counterfactual
# 1   Jan 2020             15       0.001           15.00
# 2   Feb 2020             18      -0.549           18.00
# 3 March 2020             22       0.4788           26.62
# 4 April 2020             19      -0.110           23.69

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:10:20