Home > Net >  Evaluate expression within function to return linear model
Evaluate expression within function to return linear model

Time:06-07

I am working on developing a function that creates a formula based on the input values. I want this to be able to handle expressions and evaluate them accordingly.

Here is what I have tried:

library(faraway)
formula_levels <- function(x,y, data) {
  response <- parse(text=y)
    formula_eval <- reformulate(x, response = eval(response))
    lm_mod <- lm(formula_eval, data)
return(lm_mod)
}
formula_levels('body sleep', 'log(lifespan)',mammalsleep)

However I get the following error:

Error in eval(response) : object 'lifespan' not found

It seems that I need to the response variable directly otherwise it just evaluates an empty variable. I have also tried doing the following:

response <- parse(text=data$y)

This just creates a ? in the terminal to include an input value and then R crashes.

CodePudding user response:

You do not have to parse the response, just as you do not have to pass the x variables:

formula_levels <- function(x,y, data) {
  formula_eval <- reformulate(x, y)
  lm(formula_eval, data)
}

formula_levels(c('Species', 'Sepal.Length'), 'log(Sepal.Width)', iris)

Call:
lm(formula = formula_eval, data = data)

Coefficients:
      (Intercept)  Speciesversicolor   Speciesvirginica       Sepal.Length  
           0.6483            -0.3209            -0.3242             0.1154  

formula_levels('Species Sepal.Length', 'log(Sepal.Width)', iris)

Call:
lm(formula = formula_eval, data = data)

Coefficients:
      (Intercept)  Speciesversicolor   Speciesvirginica       Sepal.Length  
           0.6483            -0.3209            -0.3242             0.1154 

Note that unless there is a specific reason as to why you are doing this, it is redundant as lm function already does what you want.

  •  Tags:  
  • r
  • Related