24

I'm using xtable to compile tables from R automatically while compiling my TeX document. The question I have is how I get the variable names in the table (which in my case are the column names in a dataframe) to be in math mode. I have stored my results in the dataframe adf.results, and essentially what I want is

colnames(adf.results) <- c(" ", "$m^r_t$", "$\delta p_t$",
                           "$R^r_t$", "$R^b_t$", "$y^r_t$")

but that simply inserts $m^r_t$ ... as the column names without interpreting them as being in math mode. Does anyone have a solution?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
hejseb
  • 2,064
  • 3
  • 18
  • 28

2 Answers2

42

as suggested in the xtable gallery vignette you should use a sanitization function (as unikum also suggested). Just some dummy code how I got it working with your example:

library(xtable)
adf.results<-matrix(0,ncol=6,nrow=4)
colnames(adf.results) <- c(" ", "$m^r_t$", "$\\delta p_t$","$R^r_t$", "$R^b_t$", "$y^r_t$")
print(xtable(adf.results),sanitize.text.function=function(x){x})

Good luck with it.

Kind regards,

FM

Community
  • 1
  • 1
FM Kerckhof
  • 1,270
  • 1
  • 14
  • 31
  • 4
    Do you know why this sanitization function works? It's taking an argument `x` and returns `x`. – Heisenberg Mar 17 '15 at 10:11
  • 3
    that is an intriguing question indeed. Running xtable without a custom `sanitize.text.function` (i.e. with `ggetOption("xtable.sanitize.text.function")` returning `NULL`) will trigger the default behavior of `print.xtable` which is to remove all characters that have a special meaning in the output format. Of course what we want in this case is to retain exactly these characters and evaluate them as TeX. Hence the seamingly useless function definition. – FM Kerckhof Mar 24 '15 at 10:13
6

Please see xtable gallery: Sanitization section (page 7 and below).

Artem Klevtsov
  • 9,193
  • 6
  • 52
  • 57