请考虑以下几点.
我想使用lapply()
来将存储在字符向量中的几个函数参数应用于其他函数.一个最小的可重复示例可以是将两个或多个"族"应用于glm()
函数.请注意,该示例对于应用此类族可能毫无意义,仅用于说明目的.
以下内容摘自?glm()
中的示例
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
data.frame(treatment, outcome, counts) # showing data
我们现在可以使用"高斯"或"泊松"族运行GLM
glm(counts ~ outcome + treatment, family = "gaussian")
glm(counts ~ outcome + treatment, family = "poisson")
这也可以通过创建具有以下族名称的字符向量来"自动"完成:
families <- c("poisson", "gaussian")
在lapply()
函数中使用这个.
但一旦运行,返回的函数调用不再返回族名称,而是返回匿名函数参数x
.
lapply(families, function(x) glm(counts ~ outcome + treatment, family = x))
#> [[1]]
#>
#> Call: glm(formula = counts ~ outcome + treatment, family = x)
#>
#> Coefficients:
#> (Intercept) outcome2 outcome3 treatment2 treatment3
#> 3.045e+00 -4.543e-01 -2.930e-01 -3.242e-16 -2.148e-16
#>
#> Degrees of Freedom: 8 Total (i.e. Null); 4 Residual
#> Null Deviance: 10.58
#> Residual Deviance: 5.129 AIC: 56.76
#>
#> [[2]]
#>
#> Call: glm(formula = counts ~ outcome + treatment, family = x)
#>
#> Coefficients:
#> (Intercept) outcome2 outcome3 treatment2 treatment3
#> 2.100e+01 -7.667e+00 -5.333e+00 2.221e-15 2.971e-15
#>
#> Degrees of Freedom: 8 Total (i.e. Null); 4 Residual
#> Null Deviance: 176
#> Residual Deviance: 83.33 AIC: 57.57
Question:
Desired outcome:
#> [[1]]
#>
#> Call: glm(formula = counts ~ outcome + treatment, family = "gaussian")
#>
#> Coefficients:
#> (Intercept) outcome2 outcome3 treatment2 treatment3
#> 3.045e+00 -4.543e-01 -2.930e-01 -3.242e-16 -2.148e-16
#>
#> Degrees of Freedom: 8 Total (i.e. Null); 4 Residual
#> Null Deviance: 10.58
#> Residual Deviance: 5.129 AIC: 56.76
#>
#> [[2]]
#>
#> Call: glm(formula = counts ~ outcome + treatment, family = "poisson")
#>
#> Coefficients:
#> (Intercept) outcome2 outcome3 treatment2 treatment3
#> 2.100e+01 -7.667e+00 -5.333e+00 2.221e-15 2.971e-15
#>
#> Degrees of Freedom: 8 Total (i.e. Null); 4 Residual
#> Null Deviance: 176
#> Residual Deviance: 83.33 AIC: 57.57
我try 了这里建议的eval(bquote(x))
:R: Passing named function arguments from vector,但这不起作用.请参阅:
lapply(families, function(x) glm(counts ~ outcome + treatment, family = eval(bquote(x))))
#> [[1]]
#>
#> Call: glm(formula = counts ~ outcome + treatment, family = eval(bquote(x)))
#>
#> Coefficients:
#> (Intercept) outcome2 outcome3 treatment2 treatment3
#> 3.045e+00 -4.543e-01 -2.930e-01 -3.242e-16 -2.148e-16
#>
#> Degrees of Freedom: 8 Total (i.e. Null); 4 Residual
#> Null Deviance: 10.58
#> Residual Deviance: 5.129 AIC: 56.76
#>
#> [[2]]
#>
#> Call: glm(formula = counts ~ outcome + treatment, family = eval(bquote(x)))
#>
#> Coefficients:
#> (Intercept) outcome2 outcome3 treatment2 treatment3
#> 2.100e+01 -7.667e+00 -5.333e+00 2.221e-15 2.971e-15
#>
#> Degrees of Freedom: 8 Total (i.e. Null); 4 Residual
#> Null Deviance: 176
#> Residual Deviance: 83.33 AIC: 57.57
由reprex package(v2.0.1)于2022-07-22创建
非常感谢.