如何在 R 中使用制表符生成 LaTeX table?

How to generate LaTeX table in R with tabs?

我正在使用 xtable 生成一些 LaTeX tables。我想这样做,以便当我复制并粘贴生成的 table 时,它会在我的 LaTeX 文件中看起来是 "lined up"。现在我有:

> 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}
>

如何使 table(至少包含真实数据的 2 行)看起来像这样?这里 & 前后的所有空格都是制表符。

\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}

有点老套,但应该可以:

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")