Created
February 4, 2017 00:58
-
-
Save mustafaascha/6bc7fa1c1dd7a7f55d6b38220b07a8a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
eqn_string <- paste(eqn_string, model_terms(nrow(mod_frame))) | |
print(eqn_string) | |
} | |
lmod <- lm(mpg ~ cyl + hp + disp, data = mtcars) | |
lm_eqn(lmod) | |
Actually, the code below is better since it adds the variables that have (NA) values in their coef.
lm_eqn <- function(model){
b <- coef(model)
names(b)[1] <- ""
eqn <- paste(format(b, digits=1), names(b), collapse=" + ")
rsq <- format(summary(model)$r.squared, digits=3)
cat("The response is equal to", eqn, ", R2 =", rsq, "\n")
invisible(model)
}
lmod <- lm(uptake ~ Plant + Treatment + conc, data = CO2)
lm_eqn(lmod)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was definitely very impressed.
Here is a modified version, which gives the correct order of variables in addition to the R2 at the end.
lmod <- lm(uptake ~ Plant + Treatment + conc, data = CO2)
lm_eqn(lmod)