建立函数给出线性回归方程 [英] Building function to give linear regression equation

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

问题描述

  lm_eqn<  -  function(模型){mod_frame < - 扫帚:: tidy(模型)
eqn_string< - sprintf(响应等于%.2f,mod_frame $ estimate [1])$ ​​b $ b model_terms< - 函数(i){
if(i == 1){return(,)}
paste(sprintf(+%.2f%s,mod_frame $ estimate [i],mod_frame $ (格式(摘要(模型)$ r.squared,数字= 3)
print(paste(eqn_string,term [i]),model_terms(i-1))
}
r2< ,model_terms(nrow(mod_frame)),R2 =,r2))
}

问题在于,它以预测变量类别的相反顺序排除了回归方程,并且以与它们在任何模型中列出的方式相反的顺序排列。 例如:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ lm_eqn(lmod)
响应等于34.18 + -0.02 disp + -0.01 hp + -1.23 cyl,R2 = 0.768

另外,有没有办法为$ R ^ 2 $添加上标?

解决方案

您可以获得 coef 的回归系数,而无需深入研究胆量你的模型对象。然后使用vectorised paste 从系数和它们的名称向量中构建您的字符串。

  lm_eqn < - 函数(模型)
{
b < - coef(模型)
名称(b)[1]< - #拦截项的默认名称(格式(b,数字= 3),名称(b),折叠=+)
rsq< - 格式(摘要(模型)
不可见(模型)
$ b $ cat(响应等于,eqn,,Rsquare =,rsq,\\\

隐形b}


So with the help of my TA, we were able to make build this function:

lm_eqn <- function(model){mod_frame <- broom::tidy(model)
eqn_string <- sprintf("The response is equal to %.2f ", mod_frame$estimate[1])
    model_terms <- function(i){
        if(i == 1){return(",")}
      paste(sprintf("+ %.2f %s", mod_frame$estimate[i], mod_frame$term[i]), model_terms(i-1))
  }
  r2 <- format(summary(model)$r.squared, digits = 3)  
  print(paste(eqn_string, model_terms(nrow(mod_frame)), "R2 =", r2))
}

The problem is that it spits off the regression equation in reverse order of the predictor variable categories and in reverse order of how they were listed in any model.

For example:

lmod <- lm(mpg ~ cyl + hp + disp, data = mtcars)
lm_eqn(lmod)
The response is equal to 34.18  + -0.02 disp + -0.01 hp + -1.23 cyl , R2 = 0.768"

Additionally, is there a way to add a superscript for the $R^2$?

解决方案

You can get the regression coefficients with coef, without having to dig into the guts of your model object. Then use vectorised paste to build your string from the vector of coefficients and their names.

lm_eqn <- function(model)
{
    b <- coef(model)
    names(b)[1] <- ""  # default name for intercept term is '(Intercept)'
    eqn <- paste(format(b, digits=3), names(b), collapse=" + ")
    rsq <- format(summary(model)$r.squared, digits=3)
    cat("The response is equal to", eqn, ", Rsquare =", rsq, "\n")
    invisible(model)
}

这篇关于建立函数给出线性回归方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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