r - 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.
解决方案
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.
推荐阅读
- php - wamp 服务器 wordpress 媒体库不显示图像
- php - 使用 Doctrine orm 和 php7 连接到 Sybase 数据库
- arrays - 如何将矩阵的单层旋转 n 个位置?
- file - 有什么方法可以让 Arduino 服务器将现有的 .html 文件发送到 Arduino 客户端?
- android - java.lang.Error:致命异常 [UnityChoreographer]
- angular - 未显示订阅值
- php - PHP - 在数据中获取 base64
- javascript - 通过纯 JavaScript 添加和删除 id
- python - 是否有自动在运算符周围添加空格的 Python IDE?
- java - Tomcat/Spring Boot 如何搜索 application.properties?