在R中用lapply调用glm时,如何保留向量中的family参数名称
解决方案
方法1:用bquote()构造并执行调用
通过bquote()将x替换为实际的family字符串,再用eval()执行,确保模型调用记录真实参数:
lapply(families, function(x) { eval(bquote(glm(counts ~ outcome + treatment, family = .(x)))) })
方法2:手动修改模型的call属性
先运行模型,再修改返回对象的call部分,替换x为实际family名称:
lapply(families, function(x) { mod <- glm(counts ~ outcome + treatment, family = x) # 将call中的family参数替换为带引号的实际名称 mod$call$family <- str2lang(sprintf('"%s"', x)) mod })
方法3:tidyverse风格的inject()实现
如果使用tidyverse工具,可结合purrr::map()和rlang::inject()注入真实参数:
library(purrr) library(rlang) map(families, function(x) { inject(glm(counts ~ outcome + treatment, family = !!x)) })
验证结果
以上任意方法运行后,返回的模型调用都会显示真实的family名称,例如:
#> [[1]] #> #> Call: glm(formula = counts ~ outcome + treatment, family = "poisson") #> #> Coefficients: #> (Intercept) outcome2 outcome3 treatment2 treatment3 #> 3.045e+00 -4.543e-01 -2.930e-01 -3.242e-16 -2.148e-16 #> ... #> #> [[2]] #> #> Call: glm(formula = counts ~ outcome + treatment, family = "gaussian") #> #> Coefficients: #> (Intercept) outcome2 outcome3 treatment2 treatment3 #> 2.100e+01 -7.667e+00 -5.333e+00 2.221e-15 2.971e-15 #> ...
内容的提问来源于stack exchange,提问作者Frederick
相关产品推荐
相关产品推荐

