在表

时间:2016-12-03 22:48:36

标签: r latex hmisc

我正在使用R中的Hmisc包来生成可重现的LaTex表,并希望抑制在booktabs模式下默认生成的一些水平线(\midrule)。我已经在这里和tex.stackexchange上筛选了Hmisc文档以及一些Hmisc解决方案,我不相信这样的任何内容已经回答了(但如果我错了请纠正我。)

这是一个应该可重现的最小例子:

library(Hmisc)    
myDF <- data.frame("foo" = c(1:10),
                       "bar" = rep(c("a","b"),5),
                       "baz" = c(21:30))

latex(myDF,
      file="",
      rowname = "",
      rowlabel = "",
      rgroup = c("Group A", "Group B", "Group C"),
      n.rgroup = c(3, 4, 3),
      booktabs = TRUE
      )

生成以下输出:

 %latex.default(myDF, file = "", rowname = "", rowlabel = "", rgroup = c("Group A",     "Group B", "Group C"), n.rgroup = c(3, 4, 3), booktabs = TRUE,     )%
\begin{table}[!tbp]
\begin{center}
\begin{tabular}{lrlr}
\toprule
\multicolumn{1}{l}{}&\multicolumn{1}{c}{foo}&\multicolumn{1}{c}{bar}&\multicolumn{1}{c}{baz}\tabularnewline
\midrule
{\bfseries Group A}&&&\tabularnewline
~~&$ 1$&a&$21$\tabularnewline
~~&$ 2$&b&$22$\tabularnewline
~~&$ 3$&a&$23$\tabularnewline
\midrule
{\bfseries Group B}&&&\tabularnewline
~~&$ 4$&b&$24$\tabularnewline
~~&$ 5$&a&$25$\tabularnewline
~~&$ 6$&b&$26$\tabularnewline
~~&$ 7$&a&$27$\tabularnewline
\midrule
{\bfseries Group C}&&&\tabularnewline
~~&$ 8$&b&$28$\tabularnewline
~~&$ 9$&a&$29$\tabularnewline
~~&$10$&b&$30$\tabularnewline
\bottomrule
\end{tabular}\end{center}
\end{table}

如何在输出中抑制部分或全部'\ midrule'?

请注意,虽然我不赞成用Hmisc来解决这个问题,但我有一些约束,rgroup标志以非常有效的方式解决。虽然我不相信xtablestargazer(例如)提供了可用的替代方案,但我肯定对其他软件包开放,只要我可以使用我的示例中提供的行分组来保留布局。

1 个答案:

答案 0 :(得分:2)

我用来处理Hmisc::latex的方法是尽可能接近它,捕获结果,用正则表达式修复它,然后打印。在这里使用正则表达式让我感到有点内疚,因为我怀疑这是一种专门用来做这些事情的方法,但经过几个小时的搜索后我就不再关心了。

在RMarkdown中,

---
title: "Table without midrules"
author: "Edward Visel"
date: "12/3/2016"
header-includes:
   - \usepackage{booktabs}
output: pdf_document
---


```{r table, message=FALSE, results='asis'}
library(Hmisc)    
myDF <- data.frame("foo" = c(1:10),
                       "bar" = rep(c("a","b"),5),
                       "baz" = c(21:30))

tb <- capture.output(latex(myDF,
      file="",
      rowname = "",
      rowlabel = "",
      rgroup = c("Group A", "Group B", "Group C"),
      n.rgroup = c(3, 4, 3),
      booktabs = TRUE, 
      where = '!htbp'    # so table prints in correct location
      ))[-1]    # so LaTeX comment at beginning doesn't print

cat(grep('\\midrule', tb, value = TRUE, invert = TRUE))    # use gsub if you prefer
```

table without midrules