在函数内将参数传递给R中的lm [英] Passing Argument to lm in R within Function
问题描述
我希望能够在函数内调用lm
并将weights
变量指定为传递给外部函数的参数,然后传递给lm
.下面是一个可重现的示例,其中,如果在函数外部对lm
进行调用,则该调用有效,但是当从包装函数中调用该调用时,会生成错误消息Error in eval(expr, envir, enclos) : object 'weightvar' not found
.
I would like to able to call lm
within a function and specify the weights
variable as an argument passed to the outside function that is then passed to lm
. Below is a reproducible example where the call works if it is made to lm
outside of a function, but produces the error message Error in eval(expr, envir, enclos) : object 'weightvar' not found
when called from within a wrapper function.
olswrapper <- function(form, weightvar, df){
ols <- lm(formula(form), weights = weightvar, data = df)
}
df <- mtcars
ols <- lm(mpg ~ cyl + qsec, weights = gear, data = df)
summary(ols)
ols2 <- olswrapper(mpg ~ cyl + qsec, weightvar = gear, df = df)
#Produces error: "Error in eval(expr, envir, enclos) : object 'weightvar' not found"
推荐答案
在注释的基础上,gear
未全局定义.当您指定要使用的数据时,它可以在独立的lm
调用中使用,因此lm
知道要从df
中提取gear
.
Building on the comments, gear
isn't defined globally. It works inside the stand-alone lm
call as you specify the data you are using, so lm
knows to take gear
from df
.
但是,gear
本身不存在于独立的lm
函数之外.这由gear
Howver, gear
itself doesn't exist outside that stand-alone lm
function. This is shown by the output of gear
> gear
Error: object 'gear' not found
您可以使用df$gear
weightvar <- df$gear
ols <- olswrapper(mpg ~ cyl + qsec, weightvar , df = df)
这篇关于在函数内将参数传递给R中的lm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!