因此,在我的助教的帮助下,我们能够构建这个函数:
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))
}
问题是,它以预测变量类别的逆序和它们在任何模型中列出的逆序推出回归方程。
例如:
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"
另外,有没有办法为$R^2$添加一个上标?
发布于 2017-02-04 08:23:54
您可以使用coef
获得回归系数,而不必深入挖掘模型对象的内部。然后使用矢量化的paste
从系数及其名称的向量构建字符串。
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)
}
https://stackoverflow.com/questions/42037462
复制相似问题