在函数内将参数传递给R中的lm [英] Passing Argument to lm in R within Function

查看:64
本文介绍了在函数内将参数传递给R中的lm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在函数内调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆