Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have a few tricks and work arounds to interesting 'features' of xtable and Latex that I'll share here.</p> <p><strong>Trick #1: Removing Duplicates in Columns and Trick #2: Using Booktabs</strong></p> <p>First, load packages and define my clean function</p> <pre><code>&lt;&lt;label=first, include=FALSE, echo=FALSE&gt;&gt;= library(xtable) library(plyr) cleanf &lt;- function(x){ oldx &lt;- c(FALSE, x[-1]==x[-length(x)]) # is the value equal to the previous? res &lt;- x res[oldx] &lt;- NA return(res)} </code></pre> <p>Now generate some fake data</p> <pre><code>data&lt;-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE), colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE), size=rnorm(100,mean=500, sd=150), age=rlnorm(100, meanlog=3, sdlog=0.5)) #generate a table datatable&lt;-ddply(data, .(animal, colour), function(df) { return(data.frame(size=mean(df$size), age=mean(df$age))) }) </code></pre> <p>Now we can generate a table, and use the clean function to remove duplicate entries in the label columns. </p> <pre><code>cleandata&lt;-datatable cleandata$animal&lt;-cleanf(cleandata$animal) cleandata$colour&lt;-cleanf(cleandata$colour) @ </code></pre> <p>this is a normal xtable</p> <pre><code>&lt;&lt;label=normal, results=tex, echo=FALSE&gt;&gt;= print( xtable( datatable ), tabular.environment='longtable', latex.environments=c("center"), floating=FALSE, include.rownames=FALSE ) @ </code></pre> <p>this is a normal xtable where a custom function has turned duplicates to NA</p> <pre><code>&lt;&lt;label=cleandata, results=tex, echo=FALSE&gt;&gt;= print( xtable( cleandata ), tabular.environment='longtable', latex.environments=c("center"), floating=FALSE, include.rownames=FALSE ) @ </code></pre> <p>This table uses the booktab package (and needs a \usepackage{booktabs} in the headers)</p> <pre><code>\begin{table}[!h] \centering \caption{table using booktabs.} \label{tab:mytable} &lt;&lt;label=booktabs, echo=F,results=tex&gt;&gt;= mat &lt;- xtable(cleandata,digits=rep(2,ncol(cleandata)+1)) foo&lt;-0:(length(mat$animal)) bar&lt;-foo[!is.na(mat$animal)] print(mat, sanitize.text.function = function(x){x}, floating=FALSE, include.rownames=FALSE, hline.after=NULL, add.to.row=list(pos=list(-1,bar,nrow(mat)), command=c("\\toprule ", "\\midrule ", "\\bottomrule "))) #could extend this with \cmidrule to have a partial line over #a sub category column and \addlinespace to add space before a total row @ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload