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

时间:2015-01-23 17:35:15

标签: r latex xtable

我正在使用xtable生成一些LaTeX表。我想这样做,以便当我复制并粘贴生成的表格时,它会看起来像#34;排队"在我的LaTeX文件中。现在我有:

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

如何使表格(至少包含真实数据的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}

1 个答案:

答案 0 :(得分:1)

Hackish,但它应该有效:

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