Error in eval(predvars, data, env) : object 'x' not found when making a function

I am trying to make a function to automate various linear regression steps. I managed to get each part working fine with manually specified variables and numbers, but replacing the necessary parts with function arguments and then using the function, I get an error.

# Top part of my full dataset for reproduction
training.dat <- data.frame(
   Money = c(16.96622074,17.03448276,14.13793103,
                 16.54827586,20.75585284,17.03448276),
      Happiness = c(67.25371402,74.6109602,28.81630076,
                 71.17892367,72.48605532,78.70280624)
)
# The function I am trying to make
# There are more below that I've left out as I believe the problem starts right at the top

my.func <- function(trainingdata, polynom, x_var, y_var){

  lmmodel.list <- list()
  for (i in 1:polynom){ 
    model_name <- paste0("lm", i,".model")                                             
    lmmodel.list[[model_name]] <- lm(y_var ~ poly(x_var, i), data = trainingdata)
  }
  
  lmfit.list <- list()
  for (i in 1:polynom){
    model_name <- paste0("lm", i,".model")
    fit_name <- paste0("lm", i,".fit")                                                 
    lmfit.list[[fit_name]] <- predict(lmmodel.list[[model_name]], newdata = trainingdata)

  }
}

When I run it using the following:

my.func(training.dat, 3, Money, Happiness)

I get the error:

Error in eval(predvars, data, env) : object 'Happiness' not found

it wasn't clear what your function should return, so I just made a list of your lists and return that.

# Top part of my full dataset for reproduction
training.dat <- data.frame(
  Money = c(
    16.96622074, 17.03448276, 14.13793103,
    16.54827586, 20.75585284, 17.03448276
  ),
  Happiness = c(
    67.25371402, 74.6109602, 28.81630076,
    71.17892367, 72.48605532, 78.70280624
  )
)
# The function I am trying to make
# There are more below that I've left out as I believe the problem starts right at the top

library(rlang)
my.func <- function(trainingdata, polynom, x_var, y_var) {
  x_var <- ensym(x_var)
  y_var <- ensym(y_var)
  lmmodel.list <- list()
  for (i in 1:polynom) {
    model_name <- paste0("lm", i, ".model")
    lmmodel.list[[model_name]] <- eval(expr(lm(!!y_var ~ 
                                                 poly(!!x_var, !!i), 
                                               data = trainingdata)))
  }

  lmfit.list <- list()
  for (i in 1:polynom) {
    model_name <- paste0("lm", i, ".model")
    fit_name <- paste0("lm", i, ".fit")
    lmfit.list[[fit_name]] <- predict(lmmodel.list[[model_name]], newdata = trainingdata)
  }
  return(list(
    models = lmmodel.list,
    fits = lmfit.list
  ))
}

my.func(training.dat, 3, Money, Happiness)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.