Search code examples
rxtable

xtable() to preserve latex function in R


I'm producing a series of tables in R that will include fractions once I report them in latex. To do this, I'm using the paste() function to apply the fraction command in r, however when I xtable it, it loses the "\f" in the beginning. Below is code. Do you know how to preserve the full function? Thanks

x <- as.vector(rbind(1, paste("\frac{",1, "}{", 2, "}", sep ="" ))) 
y <- as.vector(rbind(2, paste("\frac{", 2, "}{", 3, "}", sep ="" )))    
table<- cbind(x,y)
xtable(table)

Solution

  • Two things are needed; first, double the backslash, and second, turn off the usual text sanitizing function by passing identity (which just returns the input).

    > x <- as.vector(rbind(1, paste("\\frac{",1, "}{", 2, "}", sep ="" ))) 
    > y <- as.vector(rbind(2, paste("\\frac{",2, "}{", 3, "}", sep ="" )))    
    > print(xtable(cbind(x,y)), sanitize.text.function=identity)
    % latex table generated in R 3.0.1 by xtable 1.7-1 package
    % Wed Jul  3 10:17:21 2013
    \begin{table}[ht]
    \centering
    \begin{tabular}{rll}
      \hline
     & x & y \\ 
      \hline
    1 & 1 & 2 \\ 
      2 & \frac{1}{2} & \frac{2}{3} \\ 
       \hline
    \end{tabular}
    \end{table}