我被困在试图将" "参数传递给lm
。
我下面的2行代码可用于以下参数,例如:
model_combinations=c('.', 'Long', 'Lat', 'Elev')
lm_models = lapply(model_combinations, function(x) {
lm(substitute(Y ~ i, list(i=as.name(x))), data=climatol_ann)})
,如果我在model_combinations列表的末尾添加'lat enper',则相同的代码会失败:
model_combinations=c('.', 'Long', 'Lat', 'Elev', 'Lat+Elev')
eval中的错误(expr,envir,cenlos):未找到对象'lat lever'
我已经扫描了帖子,但无法找到解决方案。
我通常发现使用reformulate
通过字符串操作构造公式,而不是尝试使用substitute()
来修改表达式,例如。
model_combinations <- c('.', 'Long', 'Lat', 'Elev', 'Lat+Elev')
model_formulas <- lapply(model_combinations,reformulate,
response="Y")
lm_models <- lapply(model_formulas,lm,data=climatol_ann)
由于reformulate
在字符串级别上工作,因此如果元素本身是非原子(例如Lat+Elev
),则不会有问题。这里唯一的棘手情况是,如果您的data
参数或变量是在某些无法轻易找到的环境中构造的,但是通过明确的data
参数通常会避免问题。
(您也可以使用as.formula(paste(...))
或as.formula(sprintf(...))
; reformulate()
只是一个方便的包装器。)
使用as.formula
您可以做:
models = lapply(model_combinations,function(x) lm(as.formula(paste("y ~ ",x)), data=climatol_ann))
MTCARS数据集:
model_combs = c("hp","cyl","hp+cyl")
testModels = lapply(model_combs,function(x) lm(as.formula(paste("mpg ~ ",x)), data=mtcars) )
testModels
#[[1]]
#
#Call:
#lm(formula = as.formula(paste("mpg ~ ", x)), data = mtcars)
#
#Coefficients:
#(Intercept) hp
# 30.09886 -0.06823
#
#
#[[2]]
#
#Call:
#lm(formula = as.formula(paste("mpg ~ ", x)), data = mtcars)
#
#Coefficients:
#(Intercept) cyl
# 37.885 -2.876
#
#
#[[3]]
#
#Call:
#lm(formula = as.formula(paste("mpg ~ ", x)), data = mtcars)
#
#Coefficients:
#(Intercept) hp cyl
# 36.90833 -0.01912 -2.26469