rr-markdowntabulartables-package

Make table in R Markdown using tabular() and booktabs


I am using the tabular() function in the tables package to make tables in an R Markdown file. I would like to use the booktabs() option to include a horizontal rule. However, when I do so, the code from booktabs() appears in my LaTex document, even when I set the chuck option to echo=FALSE.

How can I use the booktabs() option with tabular?

Output: tables with booktabs output

And here is the code for the example:

---
title: "Making Tables"
output:
  pdf_document: default
header-includes: \usepackage{booktabs}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(tables)
library(Hmisc)
```

```{r no line, results='asis'}
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```

```{r with line, results='asis', echo = FALSE}
booktabs()
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```

Solution

  • Just use the invisible function around booktabs like this:

    ```{r with line, echo = FALSE,results= "asis"}
    invisible(booktabs())
    latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
    ```