When writing reports using R + Latex environment it’s a good idea to directly generate the tables containing results

of your calculations directly from R. This is rather a straightforward task when using commands like `latex`

.

One place when this gets a bit awkward is when you want to include some math in e.g. column names.

A simple trick that seems to work pretty well is to map your column names just before generating the latex table.

This can be done using the hash package like so:

require(Hmisc)
require(hash)
# Some data for our table
x <- 1:5
df <- data.frame(x=x, x2=x^2,x3=x^3, x0.5=sqrt(x))
# First version - without mapping
a <- latex(df ,rowlabel="",file="table.tex")
# Second version - column names mapped using a hash object
map <- function(vals){
col.map <- hash( x = "$x^1$",
x2 = "$x^2$",
x3 = "$x^3$",
x0.5 = "$\\sqrt x$")
lapply(vals, function(v)col.map[[v]])
}
colnames(df) <- map(colnames(df))
a <- latex(df, rowlabel="", file="table.mapped.tex")

After including the generated tex files in some Latex document the table without the mapping looks like this

… and using mapped column names we have:

### Like this:

Like Loading...

## Discussion

## No comments yet.