How to put a crossreference in Rbookdown? - r

I am not sure I understand this part from the documentation
the table label for a code chunk with the label foo will be tab:foo
Say I have a RMarkdown chunck such as
```{r mytable, echo=FALSE}
kable(df, booktabs=T)
```
I would consider mytabel as the label for the code chunck. That means I should be able to type a narrative that looks like:
This is my table \#ref(tab:mytable)
And the \#ref should reference the table number instead of the chucnk id. Instead I get a double (and clickable) ?? .What am I doing wrong?

In the second paragraph of the documention:
Like figures, tables with captions will also be numbered and can be referenced.
So you want to cross-reference a table, you must specify the caption argument.
You can create a empty RStudio project and or save following code as index.Rmd file. Or download
https://github.com/yihui/bookdown-minimal and replace the content of index.Rmd file with the following code. Then you can press Build Book button in the Build panel.
---
title: "A Book"
author: "Frida Gomam"
site: bookdown::bookdown_site
output:
bookdown::gitbook: default
---
# reference
This is my table \#ref(tab:mytable)
# table
```{r mytable, echo=TRUE}
knitr::kable(iris[1:10, ], booktabs=T, caption='A table of the first 10 rows of the mtcars data')
```

Related

cross reference to a table in rmarkdown with the correct table number in word document

I am trying to reference a table in a word document using bookdown package.
I wanted to add the reference id in the fig.cap parameter of the code chunk, but this is somehow not seen by the interpreter and I don't get the link to the reference.
As a workaround, I added my reference ID to the caption of the table, but here the full id ({#mysecondtable2}) is written in the figure caption and this looks ugly.
Any idea on how to solve this? Maybe LUA filter to remove the ugly anchor from the table caption? I don't understand how to do this.
---
title: "Untitled"
author: "Mario"
date: '2022-11-10'
output:
bookdown::word_document2:
toc: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
See Table \#ref(tab:myfirsttable). Or click [Table \#ref(tab:mysecondtable)](#mysecondtable2).
```{r myfirsttable, echo = FALSE}
knitr::kable(cars, caption = "First three rows of cars dataset")
```
See Table \#ref(tab:mysecondtable).
```{r mysecondtable, echo = FALSE, fig.cap='{#mysecondtable2}'}
knitr::kable(head(iris, 3),
caption='{#mysecondtable2} test')
```
EDIT:
Some strange behaviour shows, that [Table \#ref(tab:mysecondtable)](#mysecondtable) seems to work. But actually it only refers to the caption of the second table but ignores the 2 at the end...
One straight-forward solution is to wrap the table into an extra div, as one can then link to that div:
Or click [Table \#ref(tab:mysecondtable)](#mysecondtable-wrapper).
::: {#mysecondtable-wrapper}
```{r mysecondtable, echo = FALSE}
knitr::kable(head(iris, 3),
caption='test')
```
:::
A slightly less crude way is to put a span into the caption:
knitr::kable(head(iris, 3),
caption='[test]{#mysecondtable}')
The difference between the two is that the link will point at the whole table when using a div, and to the caption when using a span.

Looping on rmarkdown::render() do not print table in Word document

I am trying to include a table in a Word document but with no results. What I get in the resulting document is just a text list of the elements of the table including column names.
My code is organized in two scripts:
Script calling Markdown file KG-report.Rmd
rmarkdown::render("KG-report.Rmd", params = list(
pest.name = pest.name),
output_file = paste0("Report-", pest.name, ".docx")
Markdown script KG-report.Rmd
---
title: "Some title"
author: "me"
date: "`r Sys.Date()`"
output:
officedown::rdocx_document:
reference_docx: Simple_master_template_opinions.docx
tables:
style: Table
params:
pest.name: "Default pest"
---
```{r process-map, echo=FALSE, warning=FALSE, message=FALSE, fig.keep='all'}
# create and check directories
source("R_scripts\\PEST.PROFILE.check.pest.directories.r", local = knitr::knit_global())
# download distribution tables or load reviewed distribution table
source("R_scripts\\PEST.PROFILE.web.EPPO.distribution.table.r", local = knitr::knit_global())
knitr::kable(pest.kg.table)
etc...
After many tests and after following suggestions on word formatting (e.g. here) which did not solve the issue, it looks like the problem is related to looping on
rmarkdown::render()
If I do not use it the table is printed....
Is there any known issue about this or am I just using it in the wrong way?
Thank you
UPDATE - SOLUTION FOUND
In the end I was able to find a solution. It looked like the kable function was printing a html table in the word file which resulted in text with no table formatting. Adding the argument format = "pipe" solved the issue.

Prevent table being split in Rmarkdown

Is there a way to put my table into one page? I have a table which is broken between two pages. Here is a reproducible example:
---
output: pdf_document
---
`r rep("Text", 400)`
```{r}
# This will create a page break
knitr::kable(mtcars, caption = "A split table")
```
This produces a 2 page pdf with a broken table as follows::
There are two easy ways to do this:
1. Add a page break
If you are only using the PDF output, you can actually integrate LaTeX commands directly into the report. Therefore the \newpage command will force a pagebreak as follows:
---
output: pdf_document
---
`r rep("Text", 400)`
\newpage
```{r}
knitr::kable(mtcars, caption = "A fixed table")
```
2. Use Page Floats:
As RMarkdown uses LaTeX to build the PDF, you can take advantage of the page floats feature. This can take some getting used to, but rather than locking the figure or table in a set position, LaTeX will try and place the figure in a position which it deems "best". With tables, it will try and remove any page breaks.
Here is an example. The table will float to the second page. Make sure to update the YAML to include the header-includes: argument as well:
---
output: pdf_document
header-includes:
- \usepackage{booktabs}
---
`r rep("Text", 400)`
```{r}
knitr::kable(mtcars, format = "latex",
caption = "A caption",
booktabs = TRUE,
longtable = FALSE)
```
`r rep("Text", 200)`
If you look at the output, you will see that the second chunk of text continues on the same page as the first, and that the table is centered on the second page. This is all done automatically by LaTeX and can avoid pain down the road if you add more text before the table which might have previously caused the table to be broken again.
Hope that helps.

Internationalization R knitr Figure caption label

I want to generate a Latex document with knitr, but it does not allow me to change the label for the figure into my language. The code:
```{r rstudio, echo = FALSE, fig.cap = "RStudio IDE", fig.margin = T}
plot(pressure)
```
This generates:
However I want the caption label to read Figura: (portuguese) instead of Figure: . I added the variable lang: pt-br, which corrects for when I call it with \#ref(fig:rstudio), but does not fixes the figure label.
How to change the caption label in Rmarkdown?
You can actually include LaTeX code directly within the Rmd file to alter the settings.
As this answer explains, names like "Figure" and "Contents" are stored in macros like \figurename and \contentsname. To change them, you have to change the definition of the respective macros using \renewcommand within your preamble:
\renewcommand{\figurename}{Fig.}
\renewcommand{\contentsname}{Table of Contents}
Here's a list of the "name macros" (and their default meaning) defined by the LaTeX standard classes article, book, and report:
\abstractname [only article, report]: Abstract
\appendixname: Appendix
\bibname [only book, report]: Bibliography
\chaptername [only book, report]: Chapter
\contentsname: Contents
\figurename: Figure
\indexname: Index
\listfigurename: List of Figures
\listtablename: List of Tables
\partname: Part
\refname [only article]: References
\tablename: Table
Here is a MWE for your scenario:
---
output:
pdf_document: default
---
\renewcommand{\figurename}{YOUR LABEL}
\renewcommand{\tablename}{TABLE LABEL}
```{r Table, echo =FALSE}
knitr::kable(iris[1:5,], caption = "A table")
```
```{r pressure, echo=FALSE, fig.cap="Test Caption"}
plot(pressure)
```
Alternative Approach
The fantastic package bookdown expands a lot on the basics of RMarkdown and knitr. One thing the package allows you to set internalisation, as explained here.

How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?

I'd like to name my tables from R scripts without the automatic Table 1:... prefix when using xtable() or knitr::kable() in an .Rmd file. Output is a pdf document.
Here's a reproducible example from an .Rmd file:
---
title: "Suppress automatic table name and number"
output: pdf_document
---
```{r myirischunk, results = 'asis', tab.cap = NULL, echo = TRUE}
library(xtable)
print(knitr::kable(head(iris), caption = "I sure wish it would say Table 1.a"))
print(knitr::kable(head(iris), caption = "Please stop"))
print(xtable(head(iris), caption = "Same thing with xtable"))
```
I've seen similar questions with some suggestions here, but I can't seem to get it to work in an .Rmd file.
It turns out that I needed to add the following in the YAML section:
header-includes:
- \usepackage{caption}
AND the following somewhere before the code chunk:
\captionsetup[table]{labelformat=empty}
Now it works:
---
title: "Suppress automatic table name and number"
output: pdf_document
header-includes:
- \usepackage{caption}
---
\captionsetup[table]{labelformat=empty}
```{r myirischunk, results = 'asis', tab.cap = NULL, echo = TRUE}
print(knitr::kable(head(iris), caption = "Table 21.a - My very own table name"))
```
This has also been described here:
Get rid of captions using texreg in markdown
And yes, I'm a bit embarrased that I didn't find that answer straight away.
Anyway, thanks to daroczig for pointing me in the tex direction instead of trying to solve the problem using chunk options or something like that.
In case you also want figures the same way, modify the example by vestland to
---
title: "Suppress automatic table name and number"
output: pdf_document
header-includes:
- \usepackage[labelformat=empty]{caption}
---
and skip the \captionsetup{}.

Resources