Search code examples
rlatexxtable

How to generate LaTeX table in R with tabs?


I am generating some LaTeX tables using xtable. I'd like to make it so that when I copy and paste the generated table it would look "lined up" in my LaTeX file. Right now I have:

> library(xtable)
> x <- data.frame(matrix(1:6, nrow = 2))
> xtable(x)
% latex table generated in R 3.1.2 by xtable 1.7-4 package
% Fri Jan 23 09:25:22 2015
\begin{table}[ht]
\centering
\begin{tabular}{rrrr}
  \hline
 & X1 & X2 & X3 \\
  \hline
1 &   1 &   3 &   5 \\
  2 &   2 &   4 &   6 \\
   \hline
\end{tabular}
\end{table}
>

How can I make the table (at least the 2 rows with real data) look like this? Here all the white spaces before and after & are tabs.

\begin{table}[ht]
\centering
\begin{tabular}{rrrr}
    \hline
        &   X1  &   X2  &   X3  \\
    \hline
    1   &   1   &   3   &   5   \\
    2   &   2   &   4   &   6   \\
   \hline
\end{tabular}
\end{table}

Solution

  • Hackish, but it should work:

    library(xtable)
    x <- data.frame(matrix(1:6, nrow = 2))
    xtab = capture.output(print(xtable(x)))
    
    library(stringr)
    tab.xtab = str_replace_all(xtab, pattern = " +\\& +", "\t\\&\t")
    
    # one of these should work, depending on where this is going
    cat(tab.xtab, sep = "\n")
    paste(tab.xtab, collapse = "\n")