[R] Multiple R linear models into one Latex table

Alex Ruiz Euler rruizeuler at ucsd.edu
Mon Aug 22 01:55:38 CEST 2011



Dear community,

I had been looking for an easy way to produce latex tables from R
output. xtable() and the package apsrtable produce good outputs but they are not
exactly what I was looking for. 

I wrote this code that generates regression tables from multiple R
linear models. I want to share it because it might be
useful for someone else, and because I would appreciate comments on how to
optimize the code. I'm also open to suggestions about design or packages to include. Or pointing out bugs. I hope this is the right list to post.

Please consider it is still in a very primitive form, and the generated table might look strange for some disciplines (I come from political science).

Thanks,
Alex



## Start script


#################################
#### R models to Latex table ####
#################################


# nice() - Multiple R linear models into one Latex table.
#
#    nice(list(fit1,fit2,...,fitn)) for generic table with n models
#
# 					or
#
#  for better tables, create objects 'model.names' and 'final.varnames', then
#
#    nice(list(fit1,fit2,...,fitn), model.names, final.varnames)



nice <- function(modelos, model.names=NULL, final.varnames=NULL) {

  var.names<-vector(mode="character")
  k<-1
  for (i in 1:length(modelos)) {
    l<-length(names(coef(modelos[[i]])))
    var.names[c(k:c(k+l-1))]<-names(coef(modelos[[i]]))
    k<-k+l
  }
  var.names<-unique(var.names)

  if(is.null(final.varnames)) {
  final.varnames<-var.names
  }

  if(is.null(model.names)) {
  model.names<-paste("Model",1:length(modelos))
  }

  mat.all<-matrix(data=NA, nrow=length(var.names)*2, byrow=FALSE, ncol=length(model.names), dimnames=list(c(rep(c("coef","sd"),length=length(var.names)*2)), c(model.names)))
  dimnames(mat.all)[[1]][c(seq(1,dim(mat.all)[1], by=2))]<-var.names; dimnames(mat.all)[[1]][c(seq(2,dim(mat.all)[1], by=2))]<-""

  for (j in 1:length(modelos)) {
    mat.all[c(match(names(coef(modelos[[j]])),dimnames(mat.all)[[1]])),j]<-coef(modelos[[j]])
    mat.all[c(match(names(coef(modelos[[j]])),dimnames(mat.all)[[1]])+1),j]<-sqrt(diag(vcov(modelos[[j]])))
  }

  mat.all<-signif(mat.all, digits=3); dimnames(mat.all)[[1]][c(seq(1,dim(mat.all)[1], by=2))]<-final.varnames


  cat("\\begin{table}[!hbt]", "\n","\\caption[Short for List of Tables]{Long for this title}","\n","\\begin{center}","\n","\\begin{tabular}{llllllllll}","\n")
  cat("&",paste(model.names[1:length(model.names)-1],"&"),model.names[length(model.names)],"\\\\","\n","\\hline","\n")
  for(i in 1:dim(mat.all)[1]) {
    if(i %in% c(seq(1,dim(mat.all)[1], by=2))) { # Odd rows (coefficients)
      
  cat(dimnames(mat.all)[[1]][i],"&")
  cat(
    for (j in 1:(length(modelos)-1)) {
      if(!is.na(mat.all[i,j])) {
	p.val<-abs(mat.all[i,j]/mat.all[i+1,j])
	if(p.val>1.644) {
	  if(1.645<=p.val & p.val<1.96) cat("\\textbf{",round(mat.all[i,j], digits=5),"*}&", sep="") else {
	    if(1.96<p.val & p.val<2.576) cat("\\textbf{",round(mat.all[i,j], digits=5),"**}&", sep="") else {
	      cat("\\textbf{",round(mat.all[i,j], digits=5),"***}&", sep="")
	    }
	  }
      } else cat(round(mat.all[i,j], digits=5),"&")
    } else cat("&")
  })
  
  cat(
    for (j in length(modelos) ) {
      if(!is.na(mat.all[i,j])) {
	p.val<-abs(mat.all[i,j]/mat.all[i+1,j])
	if(p.val>1.644) {
	  if(1.645<=p.val & p.val<1.96) cat("\\textbf{",round(mat.all[i,j], digits=5),"*}", sep="") else {
	    if(1.96<p.val & p.val<2.576) cat("\\textbf{",round(mat.all[i,j], digits=5),"**}", sep="") else {
	      cat("\\textbf{",round(mat.all[i,j], digits=5),"***}", sep="")
	    }
	  }
	} else cat(round(mat.all[i,j], digits=5))
    }
   })
  cat("\\\\", "\n" )

  } else {
      cat("&",ifelse(!is.na(mat.all[i,1:(length(dimnames(mat.all)[[2]])-1)]),paste("(\\emph{",round(mat.all[i,1:(length(dimnames(mat.all)[[2]])-1)], digits=5),"})&",sep=""), paste("&")),
       ifelse(!is.na(mat.all[i,length(dimnames(mat.all)[[2]])]),paste("(\\emph{",round(mat.all[i,length(dimnames(mat.all)[[2]])], digits=5),"})",sep=""),paste(" ")),
	"\\\\", sep="", fill=TRUE)}
    }
  
  cat("\\hline","\n","\\emph{n}","&")
  cat(
      for(j in 1:(length(modelos)-1)) {
	cat(length(modelos[[j]]$residuals),"&",sep="")
      },
      for(j in length(modelos)) {
	cat(length(modelos[[j]]$residuals), "\\\\", "\n", sep="")
      }
  )
  
  cat("\\emph{Adj-R$^2$}&")
  cat(
	for(j in 1:(length(modelos)-1)) {
	if (class(modelos[[j]])[1]=="lm") {cat(round(summary(modelos[[j]])$adj.r.squared,digits=2),"&", sep="")} else {
	cat("&") 
	}
      },
      for(j in length(modelos)) {
	if (class(modelos[[j]])[1]=="lm") {cat(round(summary(modelos[[j]])$adj.r.squared,digits=2),"\\\\","\n")} else {
	cat("\\\\","\n") 
	}
      } 
    )

  cat("\\emph{AIC}&")
  cat(
	for(j in 1:(length(modelos)-1)) {
	if (class(modelos[[j]])[1]=="glm") {cat(round(summary(modelos[[j]])$aic, digits=0),"&", sep="")} else {
	cat("&")
	}
      },
      for(j in length(modelos)) {
	if (class(modelos[[j]])[1]=="glm") {cat(round(summary(modelos[[j]])$aic, digits=0),"\\\\", sep="")} else {
	cat("\\\\") 
	}
      }
    )
  cat("\n","\\hline")
  cat("\n","\\multicolumn{3}{l}{\\footnotesize{Signif. codes:  0.01 `***' 0.05 `**' 0.1 `*'}}\\\\")
  cat("\n","\\multicolumn{3}{l}{\\footnotesize{Standard errors in parentheses}}\\\\")
  cat("\n","\\end{tabular}","\n","\\end{center}", "\n", "\\end{table}", "\n")
# cat("% Suggestions: Alex R.E. <rruizeuler at ucsd.edu>","\n")
}


## End script



More information about the R-help mailing list