Skip to content

Instantly share code, notes, and snippets.

@mustafaascha
Created February 4, 2017 00:58
Show Gist options
  • Save mustafaascha/6bc7fa1c1dd7a7f55d6b38220b07a8a8 to your computer and use it in GitHub Desktop.
Save mustafaascha/6bc7fa1c1dd7a7f55d6b38220b07a8a8 to your computer and use it in GitHub Desktop.
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)
@aminfsaad
Copy link

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