[R] latex tables for 3+ dimensional tables/arrays

Dieter Menne dieter.menne at menne-biomed.de
Fri Dec 3 10:19:40 CET 2010



David Winsemius wrote:
> 
> 
> On Dec 2, 2010, at 3:47 PM, Michael Friendly wrote:
> 
>> I'm looking for an R method to produce latex versions of tables for  
>> table/array objects of 3 or more dimensions,
> 

Some time ago, I did a quick hack. Don't know if it helps, it was good
enough for my purpose.

## RNW file

\documentclass{article}
\usepackage{Sweave}
\usepackage{ctable}
\SweaveOpts{engine=R,eval=TRUE, eps=FALSE, pdf=TRUE, strip.white=FALSE,
echo=FALSE, results=hide, width=6,height=4, prefix.string=graphics/era}

\begin{document}
\section{Test FTable}

<<>>=
library(Hmisc)
df = data.frame(drug=sample(c("P","V","G","D"),100,TRUE),
                season=sample(c("Spr","Sum"),100,TRUE), 
                Hist1=sample(c("Pos","Neg","??"),100,TRUE),
                Hist2=sample(c("AZ","BZ"),100,TRUE))
ft <- ftable(drug~season+Hist1+Hist2,data=df)                
@

<<results= verbatim>>=
ft
@


<<results= tex>>=
latex.ftable = function(object,title="",caption,label,pos="!tbp",...){
  ft = format(object,quote=FALSE)
  nr = nrow(ft)
  nc = ncol(ft)
  cv = attr(object,"col.vars")
  rv = attr(object,"row.vars")
  ncolvars = length(cv)
  nrowvars = length(rv)
  
  ft[ncolvars,1:nrowvars] = ft[ncolvars+1,1:nrowvars]
 
  align1 = paste(rep("l",ncolvars),collapse="")
  align2 = paste(rep("r",nc-ncolvars),collapse="")
  cat("\\ctable[ caption={",caption,"}, label=",label,",pos=",pos,",
botcap]{",
    align1,align2,"}{} \n{\\FL\n", sep="")
  for (i in 1:ncolvars){
    head = paste("\\multicolumn{1}{c}{",ft[i,],"}",collapse="&\n",sep="")  
    if (i == ncolvars)
      cat(head, "\n\\ML\n") else
    cat(head, "\n\\NN\n")
      
  }
  for (i in (ncolvars+2):(nr)) { 
    cat(paste(ft[i,],collapse="&"))
    if (i != nr ) {
      if (substr(ft[i,1],1,1) ==' ' & substr(ft[i+1,1],1,1) !=' '){
        cat("\\ML\n")
      } else 
      cat("\\NN\n")
    }
  }
  cat("\n\\LL\n}\n")
}

latex(ft,caption,"This is an ftable",label="tab:ftable")
@

\end{document}

               



-- 
View this message in context: http://r.789695.n4.nabble.com/latex-tables-for-3-dimensional-tables-arrays-tp3070166p3070818.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list