[英]Function to run regression model with different covariates, outcome variables, and fixed effects
I want to write a function that to modify a regression model efficiently, taking arguments for (at minimum) the outcome variable, treatment variables, and fixes effects.我想编写一个 function 来有效地修改回归 model,将 arguments 用于(至少)结果变量、治疗变量和修复效果。 It would be great to go even deeper, like modifying weights.更深层次的 go 会很棒,比如修改权重。 For instance, I often want to write a model with the same covariates for many different outcomes.例如,我经常想编写一个 model ,它具有相同的协变量来处理许多不同的结果。 If I want to modify the covariate set, I'd like to do that in one line rather than going through each regression individually.如果我想修改协变量集,我想在一行中完成,而不是单独进行每个回归。
library(fixest)
dataset <- mtcars
covs_1 <- c("cyl", "disp","hp")
depvar_1 <- c("mpg")
treatment_1 <- c("vs")
# function to run models based on dep variable and covariate set
runmod <- function(depvar, treatment,covs) {
feols(as.formula(paste(c(depvar, " ~ ", treatment, paste(covs, collapse = " + ")),
data = data, cluster = "state")))
}
runmod(depvar_1, treatment_1, covs_1)
Note that fixest
natively supports multiple estimations, and you can set up formula macros to compactly add your covariates:请注意, fixest
本身支持多个估计,您可以设置公式宏来紧凑地添加协变量:
library(fixest)
# ..cov: macro stacking all the covariates
setFixest_fml(..cov = ~ cyl + disp + hp)
# multiple estimation:
# c(dep1, dep2): multiple dep. vars
# sw(var1, var2): multiple expl. vars (sw means step wise)
multiest = feols(c(mpg, qsec) ~ sw(vs, am) + ..cov, mtcars)
etable(multiest)
#> model 1 model 2 model 3 model 4
#> Dependent Var.: mpg mpg qsec qsec
#>
#> (Intercept) 36.01*** (4.466) 30.48*** (2.866) 17.77*** (1.441) 24.41*** (0.9152)
#> vs -0.9692 (1.918) 2.272** (0.6190)
#> cyl -1.446 (0.9167) -0.8345 (0.7571) -0.0530 (0.2958) -0.8165** (0.2418)
#> disp -0.0182. (0.0106) -0.0077 (0.0107) 0.0088* (0.0034) 0.0031 (0.0034)
#> hp -0.0159 (0.0151) -0.0330* (0.0156) -0.0178** (0.0049) -0.0091. (0.0050)
#> am 3.445* (1.454) -2.199*** (0.4643)
#> _______________ _________________ _________________ __________________ __________________
#> S.E. type Standard Standard Standard Standard
#> Observations 32 32 32 32
#> R2 0.77006 0.80785 0.72765 0.77703
#> Adj. R2 0.73600 0.77939 0.68731 0.74400
See the documentation on multiple estimations here and on formula macros there .请参阅此处有关多重估计的文档和此处有关公式宏的文档。
I hope this works:我希望这有效:
library(fixest)
dataset <- mtcars
covs_1 <- c("cyl", "disp", "hp")
depvar_1 <- c("mpg")
treatment_1 <- c("vs")
# function to run models based on dep variable and covariate set
runmod <- function(depvar, treatment, covs) {
formula <- paste(depvar,
" ~ ",
treatment,
" | ",
paste(covs, collapse = " + "))
feols(as.formula(formula), dataset, cluster = "am")
}
runmod(depvar_1, treatment_1, covs_1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.