Caption numbering not in sequential order when citing the captions with captioner in Rmarkdown - r-markdown

I am using captioner (https://cran.r-project.org/web/packages/captioner/vignettes/using_captioner.html) to create table captions in Rmarkdown - the main reason is because I am using huxtable for conditional formatting and exporting to word. This is the only I have found to have numbered captions.
I was trying to reference the captions but the caption number is not in sequential order when citing the captions but only if the table_nums(..., display="cite") is before the tables. I was trying to give the range of table numbers and it changed the number of the last table. I The number isn't changed if the r table_nums('third_cars_table',display = "cite") is put after the captions. Is there a way to make sure that table numbers remain in sequential order? I'd also be happy with a better solution for numbered captions.
Reproducible example:
---
title: "Untitled"
output: bookdown::word_document2
---
```{r setup, include=FALSE}
library(captioner)
library(huxtable)
library(knitr)
library(pander)
table_nums <- captioner(prefix = "Table")
fig_nums <- captioner(prefix = "Figure")
knitr::opts_chunk$set(echo = TRUE)
```
## Description of tables
I am trying to put a description of tables
and say that these results are shown table numbers ranging
from the first table (`r table_nums('first_cars_table',display = "cite")`)
to the last table (`r table_nums('third_cars_table',display = "cite")`)
```{r, results='asis',echo=FALSE,eval.after=TRUE}
tablecap1=cat(table_nums(name="first_cars_table",caption='First car table'))
kable((cars[1:5,]))
tablecap2=cat(table_nums(name="second_cars_table",caption='second car table'))
kable(cars[6:10,])
tablecap3=cat(table_nums(name="third_cars_table",caption='third car table'))
kable(cars[10:15,])
```
The results:

A (terrible) workaround is to manually give the number ordering using display = FALSE. For example, inserting the following at the start of the document will ensure t1-t5 are sequentially numbered, no matter where the tables or first citations appear:
`r table_nums('t1', display = FALSE)`
`r table_nums('t2', display = FALSE)`
`r table_nums('t3', display = FALSE)`
`r table_nums('t4', display = FALSE)`
`r table_nums('t5', display = FALSE)`
I have not examined the captioner code but I expect that the document is read from top to bottom once and hence the numbering is stored in a first come, first served basis. Thus, I am not sure there are any other ways to get around this as it would involve some kind of pre-processing stage.

Related

RMarkdown, knitr::kable shows "\begin{table}" after knitting to pdf document

One of cells in my RMarkdown document
```{r echo=FALSE}
head(data,3) %>% knitr::kable(caption = "Pierwsze 3 wiersze ze zbioru danych Lista_1.csv", digits = 2, booktabs = T)
gives weird result after knitting to pdf:
Of course there shouldn't be "\begin{table}" ,"\caption{}" and "\end{table}" parts. I use knitr::kable often and it never worked this way. Does anyone know how to fix it?
Edit: I have also noticed that all section headers (like "##Section2") below the table are centered. They shouldn't.
I've just found this question: How do I prevent kable from leaving raw latex in the final document if I include a caption in a table?
and used tip from comment (format = pandoc). It worked for me.

How to create own table in Bookdown and reference it within the text?

I am currently writing my thesis in RMarkdown using the template Oxforddown (which is ultimately based on bookdown). I have been reading the documentation but I confess I am lost. I am trying to create a table that contains an overview of the experimental conditions and items I used in my empirical study, so it is not data that I can load into R and then use the kable function on. However, I do not understand how I could generate such a table. Generating RMarkdown tables outside code chunks seems to work, but then the captions and referencing are very different than the rest of the captions used so far, which I usually set up within code chunks. Example below:
{r pilot-short7, echo=FALSE, fig.scap="Pilot 2: ....", out.width="65%", message=FALSE, fig.pos='H', fig.align = 'center'}
When I am trying to include RMarkdown tables inside a code chunks, things go wrong. What would my options be?
Any help would be very much appreciated!
I prepared a markdown template for you.
Here I made a table with flextable library.
But you can use another, which you like, f.e.: kableExtra, gt etc.
As you can see, you should put \label{tab:caption} and after refer in the text by \ref{tab:caption}.
---
title: "Hello World"
header-includes:
- \usepackage{caption}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, include = FALSE}
library(flextable)
library(dplyr)
table2 <- flextable(mtcars[1:5, 1:6])
```
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
\begin{table}[hbtp]
\captionof{table}{Text of the caption.}
\label{tab:caption}
`r table2`
\end{table}
Table \ref{tab:caption} is the baddest table in the World

Adding a letter to all table numbers in RMarkdown

I'm using RMarkdown to create Supplementary documents for a paper. These supplements contain many tables. Let's call these documents Supplement A and Supplement B. I want the table numbering to reflect the supplement letter, that is, Table A1 or Table 1A for the first table in Supplement A and so on for all tables.
How can I modify the table numbering to add a letter into the table numbering schema?
Here's an example that will produce a table with normal numbering:
---
title: "Supplement A"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="MTCars") %>%
kable_styling(latex_options="hold_position", position="left")
```
An inelegant solution using the captioner package (details provided here: https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/) can create captions and insert them manually just before the code chunk. Combining this with the Latex package caption makes it possible to remove the automatic table naming and numbering if the caption is generated within the code chunk (How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?). I've done this in the YAML with \captionsetup[table]{labelformat=empty}, but it can be done in the document body also. Either way, the caption can then be generated within the code chunk, which was important in my case.
This solution stops bookdown referencing from working (because labelformat cannot be empty), but a workaround for table referencing was provided in the link for using the captioner package (and is included below).
---
title: "Supplement A"
header-includes:
- \usepackage{caption}
\captionsetup[table]{labelformat=empty}
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(captioner)
library(stringr)
```
```{r captions}
# Create the caption(s)
caption <- captioner("Table A", FALSE)
tab_1_cap <- caption("Tab_1", "MTCars")
# Create a function for referring to the tables in text
ref <- function(x) str_extract(x, "[^:]*")
```
The following table is `r ref(tab_1_cap)`.
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption=tab_1_cap) %>%
kable_styling(latex_options="hold_position", position="left")
```
An alternative solution is avaiable via LaTeX. Add the following somewhere in the body of the document to change the default figure and table names to include the letter.
\def\figurename{Figure A}
\def\tablename{Table A}
To reference a table or figure in text use, e.g., Table A\#ref(tab:label), after defining the table label as normal.
This alone will leave a space in the table/figure caption (e.g., 'Table A 1' instead of 'Table A1'). This can be solved by adding the following to the YAML:
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
The \DeclareCaptionLabelFormat creates a function (here labeled nospace), which overrides the default caption label when called. #1 represents the label assigned to refer to tables or figures (e.g., 'Table A') and #2 represents the number of the table or figure. The captionsetup lines change the label format for all tables and figures to the format defined by 'nospace'.
Thus, the code produces, e.g., 'Table A1: Table name' as the caption. If instead you wanted, e.g., 'Table A-1: Table name', the code in \DeclareCaptionLabelFormat should be changed to {#1-#2}.
---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```
\def\figurename{Figure A}
\def\tablename{Table A}
See Table A\#ref(tab:cars) for something about cars.
(ref:cars) Table caption
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="(ref:cars)") %>%
kable_styling(latex_options="hold_position", position="left")
```
Answer inspired by: Figure name in caption using RMarkdown
Caption latex package documentation: https://ctan.org/pkg/caption

Change Default Beamer slide size

In R markdown when using Beamer slides if you try to plot you need to specify the plot sizes (unlike in the reports) so that the plots fit on a page. This can often result in the plots appearing to be squashed together, as apposed to just a smaller version of the plot.
Is there some method to change the default slide size to alleviate this problem?
I have tried
header-includes:
- \usepackage[papersize={25.6cm,19.2cm}]{geometry}
in the yaml header, and I get the error
! LaTeX Error: Missing \begin{document}.
Using R Markdown I shouldn't need to use this though.
A reproducible example is shown below
---
title: "Plots look bad"
author: "Beavis"
date: "`r format(Sys.time(), '%d/%m/%Y')`"
output: beamer_presentation
header-includes:
- \usepackage{float}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(results = 'hide')
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(cache=TRUE)
knitr::opts_chunk$set(fig.height=3.5)
```
# Introduction
```{r}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
Here, you if you run this the second slide looks like this As you can see the plot is rubbish. What is the best way to avoid this problem?
The biplot function uses par(pty = "s") to force a square plot, so it's not going to fill a rectangular slide. You can make it look better by asking the fig.height to be bigger, but then it will overflow the bottom of the slide. To prevent this, you can set both fig.height to a large number, and out.height (which will be a LaTeX measurement) to something that will fit on a slide. For example, using this chunk
```{r fig.height=10, out.height="0.8\\textheight"}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
I see this output:
I'd recommend a smaller fig.height, but your preference may be different.
Both fig.height and out.height could be specified using knitr::opts_chunk$set as defaults for all slides if you want.
You could also specify out.width="\\textwidth" for a really ugly stretched plot that fills the slide, but I wouldn't recommend it.

Adjust the output width of R Markdown HTML output

I am producing an HTML output but I am having issues with the output width of R code output.
I'm able to adjust the figure width with no difficulty but when I try to write a data table or the factor loadings, R is outputting at a fixed width which is only about a third of my screen width. This results in the columns of the table being split up rather than all of the columns displayed in a single table.
Here is a reproducible example:
---
output: html_document
---
# Title
```{r echo = FALSE, fig.width=16, fig.height=6}
x = matrix(rnorm(100),ncol=10)
x
plot(x)
```
Add this at the start of your document:
```{r set-options, echo=FALSE, cache=FALSE}
options(width = SOME-REALLY-BIG-VALUE)
```
Obviously, replace SOME-REALLY-BIG-VALUE with a number. But do you really want to do all that horizontal scrolling?
Your output is probably being wrapped somewhere around 80 characters or so.
Also, you can temporarily change the local R options for a code chunk:
```{r my-chunk, R.options = list(width = SOME-BIG-VALUE)}
```