Referencing a table in R markdown with knitr - r

It's possible to reference a figure in knitr like that:
```{r myfig}
plot(1,1)
```
Figure \ref{fig:myfig} shows ...
The same is not possible for tables, e.g.
```{r my_table, results='markup', fig.cap='capture'}
tab <- read.table('my_table.txt', sep = '\t')
kable(tab,
format='pandoc',
digits = 3,
caption =
"Description")
```
Table \ref{table:my_table} shows ...
doesn't work! Is it possible to make this work without digging into latex? If no, what would I have to do to make it work?

With format='pandoc' you need to enter the \label command in the caption.
With format='latex' the reference is automatically created as tab:chunk_label. For example,
---
output:
pdf_document
tables: true
---
```{r results='markup'}
tab <- head(iris)
knitr::kable(tab,
format='pandoc',
digits = 3,
caption = "Pandoc table\\label{tab:pandoc_table}"
)
```
```{r latex_table, results='markup'}
tab <- head(iris)
knitr::kable(tab,
format='latex',
digits = 3,
caption = "LaTeX table",
booktabs = TRUE
)
```
Table \ref{tab:pandoc_table} was done using Pandoc,
while Table \ref{tab:latex_table} used \LaTeX.

Replace table with tab \#ref(tab:my_table)

Related

How to generate automatic numbering of table titles in word using knit in Rmarkdown?

I'm doing a markdown report for my work. I need the outputs in word. Although with KABLE I can place titles on my tables, they are not numbered.
What should I add to kable () or in YAML to get automatic numbering of my tables?
crude example of what I do:
table(cars$speed) %>%
as.data.frame() %>%
kable(caption = "title",digits = 0, format.args = list( decimal.mark = ",",big.mark = "."),booktabs = T) %>%
kable_styling(latex_options = c("hold_position"))
To do this you will need to use the bookdown extensions to markdown. The following is an example rmarkdown (.Rmd) file which does want you want:
---
output:
bookdown::word_document2
---
See Table \#ref(tab:myfirsttable).
```{r myfirsttable, echo = FALSE}
knitr::kable(head(cars, 3), caption = "First three rows of cars dataset")
```
See Table \#ref(tab:mysecondtable).
```{r mysecondtable, echo = FALSE}
knitr::kable(head(iris, 3), caption = "First three rows of iris dataset")
```
Once generated the word document looks like:
For more information see:
https://bookdown.org/yihui/bookdown/a-single-document.html
https://bookdown.org/yihui/bookdown/tables.html

kableExtra stops evaluating latex code in table

I have an R Markdown table with this \rule{1cm}{0.4pt} LaTeX command in each cell of one column. The table formats just fine with kable if I do not include the kableExtra package. If I do include kabelExtra, the LaTeX command is no longer interpreted. The results are shown below, without and with kableExtra. No other change was made. The top example is my desired result.
I inspected the .tex output. kableExtra seems to format the LaTeX command as literal text: \textbackslash{}rule\{1cm\}\{0.4pt\} instead of the command shown above.
I want to use kableExtra for other features like setting column widths but I need it to interpret the LaTeX commands. I did not find anything in the manual or vignettes that seemed to address included LateX commands. Am I missing something?
Edit
I tried adding format = "latex" to the kable call when using kableExtra but undesired result remained.
MWE
---
title: "Without kableExtra"
output:
pdf_document:
keep_tex: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tibble)
library(knitr)
#library(kableExtra)
a = seq(1:3)
b = seq(4:6)
tab <- as.tibble(cbind(a,b))
tab <- add_column(tab, c = "\\rule{1cm}{0.4pt}")
```
```{r}
kable(tab,
booktabs = TRUE,
longtable = TRUE)
```
Results
When using kableExtra you should add the argument escape = FALSE to your kable() call. The escape argument let you use LaTeX commands in table.
The following works:
---
title: "Without kableExtra"
output:
pdf_document:
keep_tex: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tibble)
library(knitr)
library(kableExtra)
a = seq(1:3)
b = seq(4:6)
tab <- as.tibble(cbind(a,b))
tab <- add_column(tab, c = "\\rule{1cm}{0.4pt}")
```
```{r}
kable(tab,
booktabs = TRUE,
longtable = TRUE,
escape = FALSE)
```

Un-bold `group_rows` headings in kableExtra

Is there a way to prevent group headers from being rendered as bold when using group_rows function in kableExtra?
I have been using the amazing kableExtra package developed by #Hao to decorate tables outputted from knitr::kable. I want to add group headers, but I do not want these to be in bold. These headers are wrapped in \textbf{} when outputted to latex, and I have not been able to work out which kableExtra function does this "code decoration".
Reproducible example:
---
title: "group_rows kableExtra"
output: pdf_document
---
```{r setup, include=FALSE}
require(kableExtra)
require(knitr)
```
```{r table, results='asis'}
knitr::kable(head(mtcars), booktabs = TRUE, format = "latex") %>%
group_rows("Group 1", 2, 3)
```
#bsalzer on github is helping me recently add some customizable options to group_rows including this feature you are asking for. If you install from github, you can do things like
knitr::kable(head(mtcars), booktabs = TRUE, format = "latex") %>%
group_rows("Group 1", 2, 3, bold = F)
and that will do the trick.

How to add table caption using df_print?

In rmarkdown (I happen to be using blogdown), if we use a SQL code chunk, a table caption is added with tab.cap in the knitr code chunk. Is there a way to use tab.cap for a R code chunk that prints a tibble using df_print = "kable" in the YAML.
I know that using the kable function directly would work, but I'm looking to use df_print.
```{r}
datasets::mtcars %>%
head(2) %>%
knitr::kable(caption = "My caption")
```
Reproducible Example
---
title: Table Captions
output:
blogdown::html_page:
df_print: "kable"
---
```{r setup, include = FALSE}
library(tidyverse)
library(DBI)
db <- dbConnect(RSQLite::SQLite(), dbname = "sql.sqlite")
```
```{sql, connection=db, tab.cap = "My Caption"}
WITH twoCol(a, b) AS (SELECT 1, 2 UNION SELECT 2, 4) SELECT a, b FROM twoCol;
```
```{r print-table, tab.cap = "Sample of the users table"}
datasets::mtcars %>%
head(2)
```
This is not mean to be an an answer, and I just want to show my own opinion.
df_print is used for printing data frames, and the output of your SQL code chunk is a SQL TABLE, not a data frame.
The chunk option tab.cap may just for SQL engine, which means we have to use function kable() directly to add table caption for data frame.
PS: As in the Section 1.5:
At the moment, not all features of rmarkdown::html_document are supported in
blogdown, such as df_print, code_folding, code_download, and so on.
However, I found that the df_print is supported in blogdown.
EDIT:
sql table is always printed with kable() no matter what df_print is. We can disable sql table caption by tab.cap = NA.
A table caption can be added by defining an chunk hook (e.g. table_caption). Insert the following code snippet at the top of the .rmd file (just a simple example):
```{r table_caption, echo = FALSE}
library(knitr)
knit_hooks$set(table_caption = function(before, options, envir) {
if(!before)
paste("<table><caption>", options$table_caption,
paste0("</caption><colgroup><col width='100'></col></colgroup>",
"<thead><tr class='header'></tr></thead><tbody></tbody></table><p>"),
sep = '')
else NULL
})
```
Then table captions can be added blow the tables.
```{sql, connection=db, tab.cap=NA, table_caption="sql table caption"}
WITH twoCol(a, b) AS (SELECT 1, 2 UNION SELECT 2, 4) SELECT a, b FROM twoCol;
```
```{r print-table, table_caption = "table caption"}
datasets::mtcars %>%
head(2)
```
`

Rmarkdown table pushed to two pages when it can fit in one

I'm trying to create separate Rmd files for different tables where each table gets rendered to separate pdfs. Because of some complex formatting issues, I'm using xtable to try and pull this off. I have some tables that I anticipate will fill up a full 8.5x11.0 page with 1 inch margins. But when I render them the first page of the pdf is blank and the second page has the entire, properly formatted table. I'm looking for help to get this to work right. Here's my minimal workable example...
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r results='asis', echo=FALSE, warning=FALSE, eval=TRUE}
require(xtable)
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
size = "normalsize",
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE
)
```
This gets saved as test.Rd and I render using...
library(rmarkdown)
render("test.Rmd"
If I change the margin sizes, it seems to only affect the left and right margin. If I shrink the size of the font, it will fit on one page, but I'd like to keep the font size as is and get rid of the blank first page. Ideas? I'm a bit of a latex newbie so apologies for missing something obvious.
I think if you add the floating = FALSE argument, it should solve the problem. I think this is the LaTex equivalent of the !h here argument when you define the table. I also separated the library call from the other code (and used library instead of require), but that's stylistic and picky.
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r echo=FALSE, warning=FALSE, eval=TRUE, results='hide'}
library(xtable)
```
```{r eval=TRUE, echo=FALSE, results='asis'}
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE,
floating=FALSE
)
```
Thanks to the posting from ted-dallas, I was able to figure out that the table.placement option did what I want without having to turn off the floating...
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r results='asis', echo=FALSE, warning=FALSE, eval=TRUE}
require(xtable)
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
size = "normalsize",
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE,
table.placement = "!ht"
)
```
This generates the output I was looking for.

Resources