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"
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.
Yes. See the Examples section of ? optim and ? integrate for some R functions that accept other functions as arguments.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With