我无法尝试将“+”参数传递给 lm
。
我下面的两行代码适用于单个参数,例如:
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+Elev”,则相同的代码会失败,如下所示:
model_combinations=c('.', 'Long', 'Lat', 'Elev', 'Lat+Elev')
Error in eval(expr, envir, enclos) : object 'Lat+Elev' not found
我已经扫描了帖子,但无法找到解决方案。
最佳答案
我通常发现使用 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(...))
; 重新公式化()
只是一个方便的包装器。)
关于r - lapply 函数将单个和 + 参数传递给 LM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41269775/