将data.frame从R转置到Latex而不使用“rownumber”(和booktabs)

时间:2014-01-25 13:14:57

标签: r latex transpose

我想将R中的data.frame转换(即向量作为列)并将其导出到Latex而不使用行号,而是使用列。我希望得到这样的输出:

Tab

但是

df <- data.frame(qwertz=c("a","b","c","d","e","f"), asdfg=c("a","b"))

    qwertz asdfg
1      a     a
2      b     b
3      c     a
4      d     b
5      e     a
6      f     b

当我使用xtable和booktabs

library(xtable)
print(xtable(t(df)), include.colnames=FALSE, booktabs=TRUE)

乳胶输出是

Tab 即。

print(xtable(t(df)), include.colnames=FALSE, booktabs=TRUE)
% latex table generated in R 3.0.2 by xtable 1.7-1 package
\begin{table}[ht]
    \centering
    \begin{tabular}{rllllll}
      \toprule
      \midrule
        qwertz & a & b & c & d & e & f \\ 
         asdfg & a & b & a & b & a & b \\ 
      \bottomrule
    \end{tabular}
\end{table}

问题:如何在两行之间直接使用\midrule

我在toLatex()ENmisc Latex()尝试了Hmisc,并在阅读了这两个问题之后:

https://tex.stackexchange.com/q/25575/36408

https://tex.stackexchange.com/q/75793/36408

1 个答案:

答案 0 :(得分:2)

您可以使用add.to.row参数

library(xtable)
df <- data.frame(qwertz=c("a","b","c","d","e","f"), asdfg=c("a","b"))
df <- t(df)
n <- nrow(df)

print(xtable(df), hline.after = NULL,
      include.colnames = FALSE,
      add.to.row = list(pos = list(0, 1, n),
      command = c('\\toprule[1.5pt]\n', '\\midrule[1pt]\n', '\\bottomrule[1.5pt]\n')))
## % latex table generated in R 3.0.2 by xtable 1.7-1 package
## % Sat Jan 25 14:32:34 2014
## \begin{table}[ht]
## \centering
## \begin{tabular}{rllllll}
##   \toprule[1.5pt]
##  qwertz & a & b & c & d & e & f \\ 
##    \midrule[1pt]
## asdfg & a & b & a & b & a & b \\ 
##    \bottomrule[1.5pt]
## \end{tabular}
## \end{table}

要在longtable LaTeX环境中使用它,您可以执行类似这样的操作

print(xtable(df),
      tabular.environment = "longtable",
      floating = FALSE,
      hline.after = NULL,
      include.colnames = FALSE,
      booktabs = TRUE,
      add.to.row = list(pos = list(0, 1, n),
      command = c('\\toprule[1.5pt]\n', '\\midrule[1pt]\n', '\\bottomrule[1.5pt]\n')))
## % latex table generated in R 3.0.2 by xtable 1.7-1 package
## % Mon Jan 27 13:00:01 2014
## \begin{longtable}{rllllll}
##    \toprule[1.5pt]
## qwertz & a & b & c & d & e & f \\ 
##    \midrule[1pt]
## asdfg & a & b & a & b & a & b \\ 
##    \bottomrule[1.5pt]
## \end{longtable}