我在创建一个调用lm()
函数的函数时遇到了问题:
regresionLineal <- function (vardep, varindep1, varindep2, DATA) {
lm(vardep ~ varindep1 + varindep2, data = DATA)
}
然后我使用我之前创建的数据框(DATOS
)中的数据将其命名为...
regresionLineal(Estatura, Largo, Ancho, DATOS)
eval(expr,envir,enclos)中出现
错误:找不到从eval(expr,envir,enclos)调用的对象'Estatura‘
欢迎任何帮助..。
发布于 2016-07-04 09:28:41
您应该执行以下操作:
regresionLineal <- function (vardep, varindep1, varindep2, DATA) {
lm(paste(vardep, "~", varindep1, "+", varindep2), data = DATA)
}
其中将vardep
、varindep1
、varindep2
作为字符串进行传递。作为示例,我使用R的内置trees
数据集:
regresionLineal("Height", "Girth", "Volumn", trees)
# Call:
# lm(formula = paste(vardep, "~", varindep1, "+", varindep2), data = DATA)
# Coefficients:
# (Intercept) Girth Volume
# 83.2958 -1.8615 0.5756
然而,我不明白我们为什么要费心这么做。如果我们必须指定公式中的每个变量,为什么不简单地传递一个完整的公式呢?在这种情况下,您可以直接使用lm()
,而无需定义自己的函数。
发布于 2019-06-10 00:29:31
如果您想创建一个具有任意数量的自变量的模型,您可以使用以下方法:
create_lm <- function(data, dep, covs) {
# Create the first part of the formula with the dependent variable
form_base <- paste(dep, "~")
# Create a string that concatenates your covs vector with a "+" between each variable
form_vars <- paste(covs, collapse = " + ")
# Paste the two parts together
formula <- paste(form_base, form_vars)
# Call the lm function on your formula
lm(formula, data = data)
}
例如,使用内置的mtcars数据集:
create_lm(mtcars, "mpg", c("wt", "cyl"))
Call:
lm(formula = formula, data = data)
Coefficients:
(Intercept) wt cyl
39.686 -3.191 -1.508
缺点是模型的打印输出没有反映您对lm进行的特定调用,不确定是否有任何方法可以绕过这一点。
发布于 2021-06-17 05:31:34
我只是想为未来的读者补充一下。
我想出的解决方案(并不完美)是以下函数:
f <- function(y, x1, x2, df) {
cmd = paste0("lm(", y, " ~ ", x1, " + ", x2, ", data = ", deparse1(substitute(df)), ")")
eval(parse(text = cmd))
}
通过这样做,您可以调用,例如,
R> f("mpg", "hp", "wt", mtcars)
Call:
lm(formula = mpg ~ hp + wt, data = mtcars)
Coefficients:
(Intercept) hp wt
37.2273 -0.0318 -3.8778
与其他方法相比,主要优点是lm
的输出不会混淆变量或数据帧的名称。
也许将来的读者会理解,运行这个命令需要了解基于R的函数:parse
、deparse1
、substitute
和eval
谢谢!
https://stackoverflow.com/questions/38175775
复制相似问题