建立函数给出线性回归方程

编程入门 行业动态 更新时间:2024-10-22 22:52:42
本文介绍了建立函数给出线性回归方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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) }

更多推荐

建立函数给出线性回归方程

本文发布于:2023-10-31 06:03:43,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线性   方程   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!