在 R 中使用数据集和响应变量调用函数时出错

error when calling a function with data set and response variable in R

我正在尝试调用一个在参数中包含数据集和响应变量的函数。但是我遇到了错误。


call <- function(data,var){
  mod_3 <- lm(var ~ . , data = data)
  summary(mod_3)
}

call(iris,"Sepal.Length")

错误

错误 model.frame.default(公式 = var ~ ., 数据 = 数据, drop.unused.levels = TRUE) : 可变长度不同(找到 'Sepal.Length')

有人可以帮我解决这个问题吗?

我们可以用 pastereformulate

创建公式
call <- function(data,var){
    mod_3 <- lm(as.formula(paste(var, ' ~ .')) , data = data)
    summary(mod_3)
   }

-测试

call(iris,"Sepal.Length")

Call:
lm(formula = as.formula(paste(var, " ~ .")), data = data)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.79424 -0.21874  0.00899  0.20255  0.73103 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        2.17127    0.27979   7.760 1.43e-12 ***
Sepal.Width        0.49589    0.08607   5.761 4.87e-08 ***
Petal.Length       0.82924    0.06853  12.101  < 2e-16 ***
Petal.Width       -0.31516    0.15120  -2.084  0.03889 *  
Speciesversicolor -0.72356    0.24017  -3.013  0.00306 ** 
Speciesvirginica  -1.02350    0.33373  -3.067  0.00258 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3068 on 144 degrees of freedom
Multiple R-squared:  0.8673,    Adjusted R-squared:  0.8627 
F-statistic: 188.3 on 5 and 144 DF,  p-value: < 2.2e-16