Search code examples
rlatexsweavextable

xtable and header alignment


Is it possible to have a header alignment in xtable which is different from the alignment used in the rest of the table? In my case, I want my header to be center aligned, but the table itself should be right aligned.


Solution

  • To do that in LaTeX you stick your headers into a \multicolumn thing to specify the alignment you want:

    \begin{tabular}{rrr}
      \hline
     & \multicolumn{1}{c}{x} &\multicolumn{1}{c}{y} \\ 
      \hline
    1 &   1 & 0.17 \\ 
      2 &   2 & 0.63 \\ 
      3 &   3 & 0.95 \\ 
      4 &   4 & 0.57 \\ 
      5 &   5 & 0.65 \\ 
       \hline
    \end{tabular}
    

    The print.xtable function uses the names of the xtable object as the headers. So if you rename your xtable object:

    > d=data.frame(x=1:5,y=runif(5))  # sample data frame
    > dx=xtable(d) # make an xtable
    > names(dx)=c("\\multicolumn{1}{c}{x}","\\multicolumn{1}{c}{y}")
    

    then that's most of the work done, you just have to print it overriding the sanitization function of print.xtable:

    > print.xtable(dx,sanitize.colnames.function=function(x){x})
    % latex table generated in R 2.15.1 by xtable 1.7-0 package
    % Thu Feb 21 15:28:11 2013
    \begin{table}[ht]
    \begin{center}
    \begin{tabular}{rrr}
      \hline
     & \multicolumn{1}{c}{x} & \multicolumn{1}{c}{y} \\ 
      \hline
    1 &   1 & 0.78 \\ 
      2 &   2 & 0.34 \\ 
      3 &   3 & 0.88 \\ 
      4 &   4 & 0.45 \\ 
      5 &   5 & 0.54 \\ 
       \hline
    \end{tabular}
    \end{center}
    \end{table}
    

    otherwise it does

    & $\backslash$multicolumn\{1\}\{c\}\{x\} & $\backslash$multicolumn\{1\}\{c\}\{y\} \\ 
    

    How's that?