问题在于,它以预测变量类别的相反顺序排除了回归方程,并且以与它们在任何模型中列出的方式相反的顺序排列。 例如: $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 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) }
更多推荐
建立函数给出线性回归方程
发布评论