R officedown::rdocx_document, templates and styles - r-markdown

I am trying to nut out how to use a company word document as a rdocx_doxument template for R markdown using the officedown package.
---
title: Company Report Title
author: Ross
date: 3/3/2022
output:
officedown::rdocx_document: default
---
# Introduction
Identifying default table and figure caption styles
```{r plot, fig.cap="My plot caption"}
plot(cars)
```
# Table
```{r, message = FALSE, warning=FALSE}
library(flextable)
cars |> head(6) |> flextable() |>
set_caption("Caption for table")
```
The style from this example gives an 'Image Caption' style for the plot and a 'Table Caption' style for the table.
Now try using the company reference template
---
title: Company Report Title
subtitle: Report subtitle
author: Ross
date: 3/3/2022
output:
officedown::rdocx_document:
reference_docx: company_report_template.docx
mapstyles:
Image Caption: ['Caption']
Table Caption: ['Caption']
Title: ['CoverTitle']
---
# Introduction
How to use mapstyles to avoid redefining company word template styles.
```{r plot, fig.cap="My plot caption"}
plot(cars)
```
# Table
```{r, message = FALSE, warning=FALSE}
library(flextable)
cars |> head(6) |> flextable() |>
set_caption("Caption for table")
```
In the word template file there is a style defined for both figure and table captions called 'Caption' and a style called 'CoverTitle' for the Title.
The rendering error message is
Error: could not find style "Caption". In addition: Warning message:
paragraph style for plots "Figure" has not been found in the
reference_docx document. Style 'Normal' will be used instead.
Execution halted
The template file does have a 'Caption' style defined.
Wondered if someone can help me fathom this out?
I am very reluctant to change the styles in the company word template file.
Thanks
Screenshot of rmarkdown header, render error and word template file showing style

Related

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

How to embed highcharter in rmarkdown to share (not a loop)

I cannot get two simple highcharter charts in an Rmarkdown file I want to share. It works fine and renders in my PC or Mac, but when I share the file, people only see text.
They are not part of a loop, as mentioned in few articles. They are just two charts. For the reproducible example, I literally just opened a new rmarkdown doc and selected html. I replaced the "summary table" of cars with highcharter code. I even tried htmltools::tagList(chart1, chart2) and it does not work.
I am supplying the code. If you please show me how to do it with one chart, I can do it with the second.
Thank you.
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))
I apologize if the tick marks hide the code background, but the three chunks are wrapped with the three tickmarks at the beginning and end of each chunk.
Thank you again.
Yes the code below produces the file below the code. I now have an entire .html file that has the highchart self contained in the file.
---
output:
html_document:
self_contained: yes
mode: selfcontained
---
{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))

Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown

Is there a way to automatically number the figures in captions when I knit R Markdown document into an HTML format?
What I would like is for my output to be the following:
Figure 1: Here is my caption for this amazing graph.
However, I am currently getting the following:
Here is my caption for this amazing graph.
Here is my MWE:
---
title: "My title"
author: "Me"
output:
html_document:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```
I have read that this issue is resolved with Bookdown but I've read the Definitive Guide to Bookdown, cover to cover, and can't find it.
If you wish to have numbered figures, you will need to use an output format provided by bookdown. These include html_document2, pdf_document2 etc. See here for a more comprehensive list of options.
Changing your document example html_document to bookdown::html_document2 will resolve your problem.
---
title: "My title"
author: "Me"
output:
bookdown::html_document2:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```
If you want to label tables created by knitr::kable, you will need to specify the caption within the table call itself
```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```

How to set df_print to tibble in markdown for a single R code chunk

I would like to show, in an rmarkdown document, the printed output of a tibble as shown in the console. i.e.
First line: dimension summary;
then the column headers;
then classes of variables;
then first 10 lines of the tibble;
then number of rows not shown.
However, by default, tibbles and other data.frame objects are automatically converted to a tabbed, paginated table showing all contents.
I note that the option to turn off this default behaviour can be set for a whole markdown document by changing the df_print option to tibble in the YAML.
However, how do I set the df_print option to tibble for just a single R code chunk, so that I can show in an Rmarkdown document what the user will see on the console?
Thanks,
Jon
There's no need to touch the global setting. You can explicitly call the print function tibble:::print.tbl_df(df)
Example:
title: "Untitled"
author: "TC"
date: "7/27/2018"
output:
html_document:
df_print: "kable"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## print tibble
```{r}
df <- tibble::as.tibble(mtcars)
tibble:::print.tbl_df(head(df))
```
## print kable (set in YAML header)
```{r}
head(df)
```
output html

Knitr/kable: table moving to the end of page when adding caption/figure label

I'm somewhat new to R Markdown, so apologies if this is silly. I'm preparing a pdf report using R Markdown/Knitr, and running into a problem where, if I try to include a styled table using kable, it moves the table to the bottom of the page.
Here is an example of the code:
---
title: "Testing"
output:
pdf_document:
fig_caption: yes
tables: true
---
```{r setup, include=FALSE}
library(knitr)
library(kableExtra)
```
Section 1: In Table \ref{fig:table1} below...
```{r table1, echo=FALSE}
kable(head(mtcars[,1:4],4), format = "latex", align = "c", caption ="\\label{fig:table1}Table Caption") %>%
column_spec(1, bold = T, width = "6em") %>%
kable_styling(position = "center")
```
Section 2: Lorem ipsum dolor sit amet
The PDF this outputs for me has "section 1" and "section 2" following each other, with the table at the very bottom of the page.
I have tried removing the caption, and using fig.cap at the start of the chunk. Although my table stays where it should, it doesn't generate a caption at all, and references to the figure turn into ??.
What works: getting rid of kableExtra, changing format from latex to pandoc. The table stays where it should, and I get the captions, but the table loses the extra formatting that I'd really like to have for the report.
What am I doing wrong? Thanks for your help!
Edit: Sorry! I'd like for the table to show up where I put it (after "section 1", before "section 2"). Like below, only with a caption/figure label. (The linked image is what I get if I get rid of the caption arg in that code chunk above)