首页 > 解决方案 > object '...' not found in R Functions with lm -->> (Error in eval(predvars, data, env) : object '...' not found)

问题描述

I'm using the moderndrive package to calculate a linear regression but using a function. I am trying to create a function where i can just pass in two selected columns(e.g deaths & cases, titles of the columns) from my data frame (Rona_2020). Below is the function...

score_model_Fxn <- function(y, x){
  score_mod <- lm(y ~ x, data = Rona_2020)
  Reg_Table <- get_regression_table(score_mod)
print(paste('The regression table is', Reg_Table))
}

when I run the function ...

score_model_Fxn(deaths, cases)

I get ...

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

What should i do? I have looked several similar issues but to no avail.

标签: rfunctiondataframedata-analysislm

解决方案


What you want to do by passing deaths and cases is called non-standard evaluation. You need to combine this with computing on the language if you want to run a model with the correct formula and scoping. Computing on the language can be done with substitute and bquote.

library(moderndive)
score_model_Fxn <- function(y, x, data){

  #get the symbols passed as arguments:
  data <- substitute(data)
  y <- substitute(y)
  x <- substitute(x)

  #substitute them into the lm call and evaluate the call:
  score_mod <- eval(bquote(lm(.(y) ~ .(x), data = .(data))))

  Reg_Table <- get_regression_table(score_mod)

  message('The regression table is') #better than your paste solution
  print(Reg_Table)

  invisible(score_mod) #a function should always return something useful
}

mod <- score_model_Fxn(Sepal.Length, Sepal.Width, iris)
#The regression table is
## A tibble: 2 x 7
#  term        estimate std_error statistic p_value lower_ci upper_ci
#  <chr>          <dbl>     <dbl>     <dbl>   <dbl>    <dbl>    <dbl>
#1 intercept      6.53      0.479     13.6    0         5.58    7.47 
#2 Sepal.Width   -0.223     0.155     -1.44   0.152    -0.53    0.083

print(mod)
#
#Call:
#lm(formula = Sepal.Length ~ Sepal.Width, data = iris)
#
#Coefficients:
#(Intercept)  Sepal.Width  
#     6.5262      -0.2234  

You could have the function return Reg_Table instead if you prefer.


推荐阅读