Skip to content

Instantly share code, notes, and snippets.

@paulrougieux
Last active December 31, 2015 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulrougieux/7979963 to your computer and use it in GitHub Desktop.
Save paulrougieux/7979963 to your computer and use it in GitHub Desktop.
# Function to output latex equation based on an estimated model # The goal is to display an estimated equation in latex form with coefficients in parenthesis # Output can be used in an R Markdown file, provided the chunk option # {r, results='asis'} has been set
# Functions usefull to display estimated equations
# Author: Paul Rougieux
# Function to output LaTeX equation based on an estimated model
# The goal is to display an estimated equation in latex form with coefficients in parenthesis
# Output can be used in an R Markdown file, provided the chunk option
# {r, results='asis'} has been set
lmdisplay = function(model){
coefs = round(data.frame(t(summary(model)$coefficients[,1:2])),3)
R2 = round(summary(model)$r.squared,3)
# Display a firt line with estimated equation
cat("$$")
# Name of the explained variable
cat(names((model$model[1])), " = ")
cat(paste("\\underset{(", coefs$X.Intercept.[2],")}",
"{",coefs$X.Intercept.[1],"}", sep=""))
for (i in c(2:length(coefs))){
if( coefs[1,i]>=0){ # write a plus for positive coefs
cat("+")
}
cat("\\underset{(", coefs[2,i],")}", sep="")
cat("{",coefs[1,i],"} ",names(coefs[i])," ", sep="")
}
cat("$$ ")
# Display a second line with multiple R squared and n= dataset length
cat("$$")
cat("R^2=",R2,", n=", nrow(model$model), sep="")
cat("$$")
}
if(interactive()){
# Example for testing, based on Wooldridge introductory econometrics third edition
vote1 = read.csv("dataset/paul/vote1.csv", na.strings=".")
vote1.lm = lm(voteA ~ lexpendA + lexpendB + prtystrA, data=vote1)
lmdisplay(vote1.lm)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment