Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Argument to lm in R within Function

Tags:

r

lm

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"
like image 775
Michael Avatar asked Dec 02 '14 23:12

Michael


People also ask

How do you pass a function as an argument in R?

Adding Arguments in R We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis. Below is an implementation of a function with a single argument.

Can functions take another function as an argument in R?

Yes. See the Examples section of ? optim and ? integrate for some R functions that accept other functions as arguments.

What does lm () do in R?

The lm() function is used to fit linear models to data frames in the R Language. It can be used to carry out regression, single stratum analysis of variance, and analysis of covariance to predict the value corresponding to data that is not in the data frame.

What is the general format of the lm () function?

The lm() function Note that the formula argument follows a specific format. For simple linear regression, this is “YVAR ~ XVAR” where YVAR is the dependent, or predicted, variable and XVAR is the independent, or predictor, variable.


1 Answers

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.

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

You can pass the gear into the function using df$gear

weightvar <- df$gear
ols <- olswrapper(mpg ~ cyl + qsec, weightvar , df = df)
like image 90
tospig Avatar answered Sep 25 '22 02:09

tospig