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

如何用fixest::sunab基于日度面板按月度分组估计并保留日期固定效应?

基于日度面板用fixest::sunab实现月度分组点估计的解决方案

核心需求

基于日度层面面板数据,使用fixest::sunab进行事件研究估计,保留日度日期固定效应的同时,将点估计按月度时间间隔分组,同时解决从未处理组被模型丢弃的问题。

解决方案步骤

1. 修正从未处理组的编码

无需将从未处理组的处理日期设为极早的2001-01-01(会导致相对时间范围过大,模型运行极慢),而是将其设为样本期结束后的日期,既不会被模型丢弃,又不会干扰处理组的估计:

library(tidyverse)
library(fixest)
library(lubridate)

# 生成示例面板数据
panel_dates <- seq(as_date("2016-01-01"), as_date("2022-12-31"), by = "day") %>% 
  as_tibble() %>% 
  rename(date = value)

districts <- c(1:20, 22, 24, 25) %>% 
  as_tibble() %>% 
  rename(district = value) %>% 
  filter(district != 13)

panel_dates <- panel_dates %>% cross_join(districts)

treatments <- tibble(
  district = c(1:20, 22, 24, 25),
  treatment_dates = as_date(c(
    "2018-05-16", "2018-01-29", "2018-03-16", "2017-01-13", "2017-10-12", "2018-03-28",
    rep(NA, 17)
  ))
)

final_panel <- panel_dates %>% 
  left_join(treatments, by = "district") %>% 
  mutate(yvar = rnorm(n = row_number()))

# 处理从未处理组:替换NA为样本结束后日期
final_panel <- final_panel %>% 
  mutate(treatment_dates = if_else(is.na(treatment_dates), as_date("2023-01-01"), treatment_dates))

2. 自定义月度分箱函数

通过自定义函数,将每个观测的**相对时间(距离处理日期的天数)**转换为月度分组,实现点估计的月度聚合:

# 定义月度分箱函数:将相对天数映射为月度区间
month_bin <- function(x) {
  # x = date - treatment_dates,即相对天数
  months_rel <- floor(x / 30.44) # 按平均每月30.44天转换为相对月份
  # 限制区间范围(可根据研究需求调整)
  months_rel <- if_else(months_rel < -24, -24, months_rel) # 提前超过24个月统一归为-24
  months_rel <- if_else(months_rel > 24, 24, months_rel) # 滞后超过24个月统一归为24
  # 转换为可读性更强的因子标签
  factor(
    months_rel, 
    levels = seq(-24, 24), 
    labels = paste0(c(rep("提前",24), "当月", rep("滞后",24)), abs(seq(-24,24)))
  )
}

3. 使用sunab结合bin参数估计模型

在sunab中传入自定义分箱函数到bin参数,同时保留日度date和district固定效应:

# 估计模型:设置参考期为提前6个月(可按需调整)
model <- feols(
  yvar ~ sunab(period = date, cohort = treatment_dates, ref.c = -6, bin = month_bin) | district + date,
  data = final_panel
)

# 查看估计结果
summary(model)

# 绘制月度分组的事件研究图
iplot(model, main = "月度分组事件研究估计")

关键说明

  • 从未处理组处理逻辑:将其处理日期设为样本后日期,确保它们的相对时间均为负数,不会进入处理后的分组区间,同时避免模型丢弃该组。
  • bin参数的作用:通过自定义分箱函数,将原本按日度的相对时间估计,聚合为月度层面的点估计,同时保留了原始日度数据的date固定效应。
  • 性能优化:避免了原方法中极宽的相对时间范围,将估计量数量从数千个(日度)降到数十个(月度),大幅提升模型运行速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:27:02