如何在R中基于多向量迭代运行多个fixest回归?
批量实现fixest包的多组合回归分析
完全可以实现这种批量回归,下面是具体的实现思路和代码:
实现步骤
生成所有回归组合
通过expand.grid()生成officer_race、primary_ind、outcome三个向量的所有笛卡尔积组合,确保覆盖所有需要运行的回归场景。批量执行回归并收集结果
用purrr包的pmap()函数遍历每个组合,针对每个组合完成:- 筛选对应警官种族的数据集子集
- 检查当前回归的因变量和自变量是否存在于数据中(避免因数据缺失变量报错)
- 若变量存在且子集非空,运行
feols()回归;否则返回对应提示信息
完整代码
# 加载所需包 library(fixest) library(tibble) library(purrr) # 用户提供的数据 analysis <- tibble( off_race = c("hispanic", "hispanic", "white","white", "hispanic", "white", "hispanic", "white", "white", "white","hispanic"), any_black_uof = c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), any_black_arrest = c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), prop_white_scale = c(0.866619646027524, -1.14647499712298, 1.33793539994219, 0.593565300512359, -0.712819809606193, 0.3473585867755, -1.37025501425243, 1.16596624239715, 0.104521426674564, 0.104521426674564, -1.53728347122581), prop_hisp_scale = c(-0.347382203637802, 1.54966785579018, -0.833021026477168, -0.211470492567308, 1.48353691981021, 0.421968013870802, 2.63739845069911, -0.61002505397242, 0.66674880256898,0.66674880256898, 2.93190487813111) ) # 需遍历的向量组 officer_race = c("black", "white", "hispanic") primary_ind <- c("prop_white_scale","prop_hisp_scale","prop_black_scale") outcome <- c("any_black_uof","any_white_uof","any_hisp_uof","any_black_arrest","any_white_arrest","any_hisp_arrest","any_black_stop","any_white_stop","any_hisp_stop") # 生成所有回归组合 reg_combinations <- expand.grid( officer_race = officer_race, primary_ind = primary_ind, outcome = outcome, stringsAsFactors = FALSE ) # 批量运行回归 reg_results <- pmap(reg_combinations, function(officer_race, primary_ind, outcome) { # 筛选对应种族的数据集 data_subset <- analysis[analysis$off_race == officer_race, ] # 检查变量是否存在于数据中 if (!all(c(outcome, primary_ind) %in% colnames(data_subset))) { return(paste("变量缺失:", paste(setdiff(c(outcome, primary_ind), colnames(data_subset)), collapse = ", "))) } # 检查子集是否非空 if (nrow(data_subset) == 0) { return(paste("无对应种族数据:", officer_race)) } # 构建公式并运行回归 formula <- as.formula(paste(outcome, "~", primary_ind)) feols(formula, data = data_subset) }) # 给结果列表命名,方便识别 names(reg_results) <- with(reg_combinations, paste(outcome, "~", primary_ind, "|", officer_race)) # 查看结果示例(比如前5个) reg_results[1:5]
注意事项
- 你提供的
analysis数据中缺少prop_black_scale、any_white_uof等多个变量,代码中加入了变量存在性检查,避免运行报错,这类情况会返回对应的提示信息。 - 对于
officer_race = "black"的情况,当前数据中没有对应行,代码会返回“无对应种族数据:black”的提示。
内容的提问来源于stack exchange,提问作者sd3184
相关产品推荐
相关产品推荐

