在R中使用线性回归创建新函数: [英] Creating new Functions with Linear Regression in R :

查看:63
本文介绍了在R中使用线性回归创建新函数:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建调用 lm()函数的函数时遇到麻烦:

I'm having a trouble when creating a function that calls the lm() function:

regresionLineal <- function (vardep, varindep1, varindep2, DATA) {
  lm(vardep ~ varindep1 + varindep2, data = DATA)
  }

然后我使用先前创建的数据帧( DATOS )中的数据进行调用...

Then I call it using data from a data frame I created previously (DATOS)...

regresionLineal(Estatura, Largo, Ancho, DATOS)

eval(expr,envir,enclos)中的错误:找不到对象'Estatura'调用来自:eval(expr,envir,enclos)

Error in eval(expr, envir, enclos) : object 'Estatura' not found Called from: eval(expr, envir, enclos)

任何帮助都将受到欢迎...

Any help will be welcome...

推荐答案

您应该这样做:

regresionLineal <- function (vardep, varindep1, varindep2, DATA) {
  lm(paste(vardep, "~", varindep1, "+", varindep2), data = DATA)
  }

您在其中将 vardep varindep1 varindep2 作为字符串传递.例如,我使用R的内置 trees 数据集:

where you pass in vardep, varindep1, varindep2 as strings. As an example, I use R's built-in trees dataset:

regresionLineal("Height", "Girth", "Volumn", trees)
# Call:
# lm(formula = paste(vardep, "~", varindep1, "+", varindep2), data = DATA)

# Coefficients:
# (Intercept)        Girth       Volume  
#     83.2958      -1.8615       0.5756  

但是,我不明白为什么我们要这么做.如果必须在公式中指定每个变量,为什么不简单地传递完整的公式呢?在这种情况下,您可以直接使用 lm()而不定义自己的函数.

However, I don't see why we bother doing this. If we have to specify every variable in the formula, why not simply pass in a complete formula? And in that case, you can use lm() directly without define your own function.

这篇关于在R中使用线性回归创建新函数:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆