如何在R自定义函数中调用fixest包的feols回归并提取系数与标准误
问题解决方法
错误原因
报错核心原因是
feols的公式解析规则与lm不同:lm允许公式中直接使用外部向量(比如df[[col]]提取的向量),但feols要求公式内的变量必须是传入数据框中存在的列名,直接在公式中写df[[col1]]会被feols判定为数据中不存在的变量,导致运行失败。
正确实现代码
方法1:公式字符串拼接
estimation_fun <- function(col1, col2, df) { # 构造公式字符串再转为formula对象 formula_str <- paste0(col1, " ~ ", col2, " | Card + Date") regression <- feols(as.formula(formula_str), data = df) est <- tidy(regression)$estimate se <- tidy(regression)$std.error output <- list(estimate = est, std_error = se) return(output) } # 测试调用,注意原测试代码中传入的数据集名错误,你构造的数据集是data不是example estimation_fun("A", "B", data)
方法2:使用fixest自带的xpd函数(更推荐)
xpd是fixest官方提供的动态公式构造工具,适配性更强,适合复杂场景:
estimation_fun <- function(col1, col2, df) { # 使用{{}}注入变量值构造公式 regression <- feols(xpd({{col1}} ~ {{col2}} | Card + Date), data = df) est <- tidy(regression)$estimate se <- tidy(regression)$std.error output <- list(estimate = est, std_error = se) return(output) } # 调用测试 estimation_fun("A", "B", data)
如果你需要批量运行多组回归,可以把待回归的自变量、因变量组合成两列的tibble,再用purrr::pmap批量调用上述函数,即可一次性返回所有回归结果。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

