Format Captions in R Markdown for Word Output - r

Default R Markdown captions in Word appear as:
Figure 1: Figure Title
Table 1: Table Title
I would like to format my captions so that the Figure 1/Table 1 is bold and the title is italic on the next line. This is the APA style of captions:
Figure 1
Figure Title
I have been trying to figure out an easy way to do this, but can't seem to find a solution. (If figure captions can be above figure, rather than below, that would also be great!). Here is a minimal reprex:
---
title: "Untitled"
author: "Test"
date: "11/8/2020"
output:
bookdown::word_document2: default
---
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(flextable)
{r table, tab.cap="Descriptives", echo=FALSE, message=FALSE, warning=FALSE}
psych::describe(cars) %>%
as.data.frame() %>%
flextable() %>%
set_table_properties(layout = "autofit", width = 1)
{r fig, fig.cap="Pressure Figure", echo=FALSE, message=FALSE, warning=FALSE}
plot(pressure)

For tables you can do it with officedown, officer and flextable packages, styling in reference_doxc, and by taking the advantage of "\n\n" for tables.
In yaml in the pre argument you set up a prefix for every table and a separator between the number and the title itself.
---
title: "Untitled"
author: "Test"
date: "11/8/2020"
output:
officedown::rdocx_document:
tables:
caption:
pre: 'Table '
sep: ''
---
With
tab.cap.fp_text = officer::fp_text_lite()
you can define the formatting of the caption prefix. In APA style it would be bold without italics, preferrably configured in the global knitr options, e.g.
knitr::opts_chunk$set(tab.cap.fp_text = officer::fp_text_lite(italic = FALSE, bold = TRUE))
And you add
"\n\n"
to the table caption to produce a new line
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, tab.cap.fp_text = officer::fp_text_lite(italic = FALSE, bold = TRUE))
library(tidyverse)
library(flextable)
{r table, tab.cap="\n\nDescriptives", echo=FALSE, message=FALSE, warning=FALSE}
psych::describe(cars) %>%
as.data.frame() %>%
flextable() %>%
set_table_properties(layout = "autofit", width = 1)
The last thing is to create a reference_doxc in which you add italics to the table caption style. The caption prefix is not affected, as you control it with the knitr options.

Related

Rotate table pdf output from Markdown

I want to rotate table output by 90 degrees on pdf. I am using markdown to generate a report and kable to display the tables in a loop. If possible, I would like to continue using kable since there are lot of other things which are dependent on it that I haven't included in this MWE.
This is a simple example using iris dataset. I tried using landscape function from this post Rotate a table from R markdown in pdf
---
output: pdf_document
header-includes:
\usepackage{lscape}
\usepackage{pdfpages}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
Report page -
```{r results='asis'}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[i:(i+5), ], format = "latex", align = "c", booktabs = TRUE,
longtable = TRUE, row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```
But this only rotates the page number keeping the table as it is.
I am actually looking for a solution which provides me the output in this way -
To clarify, all the pages with table data in it (3 for this example) should be rotated whereas rest of them should remain as it is. Also, I need longtable = TRUE in kable since in my actual example I am printing lot of rows.
Use package rotating
I added a simple example for you.
---
title: "test"
header-includes: \usepackage[figuresright]{rotating}
#or \usepackage[figuresleft]{rotating}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include = FALSE}
library(flextable)
ft <- flextable(head(mtcars))
```
\begin{sidewaysfigure}
`r ft`
\end{sidewaysfigure}
```
Further you can modify it for your tasks ;)
I found another way using rotatebox.
---
output: pdf_document
header-includes:
\usepackage{lscape}
\usepackage{pdfpages}
\usepackage{graphicx}
\usepackage[figuresright]{rotating}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
Report page -
```{r results='asis', warning=FALSE, message=FALSE}
library(knitr)
library(kableExtra)
for (i in 1:3) {
cat('\\rotatebox{90}{')
print(kable(iris[i:(i+5), ], format = "latex", align = "c", booktabs = TRUE,
row.names = FALSE))
cat('}')
cat("\n\\newpage\n")
}
```

Align multiple tables side by side using the flextable R package in R markdown

Folks, how do I align multiple tables side by side using the flextable R package in R markdown?
---
title: "flextables side by side"
output:
word_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
library(dplyr)
```
## Please, plot these tables side by side!
```{r pressure, echo=FALSE}
flextable(pressure[1:7,])%>% set_caption(caption = "Table 1")
flextable(cars[1:5,])%>% set_caption(caption = "Table 2")
```
There are examples for other packages:
Align multiple tables side by side
Rmarkdown side-by-side tables spacing
This is a solution for both HTML and Word output that do not require transforming tables as images.
---
title: "flextables side by side"
output:
officedown::rdocx_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
library(dplyr)
library(officedown)
```
## two tables side by side
<!---BLOCK_MULTICOL_START--->
::::: {.row}
::: {.col-xs-12 .col-md-6}
```{r echo=FALSE}
flextable(pressure[1:7,])%>%
autofit() %>%
set_caption(caption = "Table 1")
```
`r officer::run_columnbreak()`
:::
::: {.col-xs-12 .col-md-6}
```{r echo=FALSE}
flextable(cars[1:5,])%>%
autofit() %>%
set_caption(caption = "Table 2")
```
:::
:::::
<!---BLOCK_MULTICOL_STOP{widths: [4,2], space: 0.1, sep: false}--->
blah blah blah
Word output:
HTML output:
Note it is not possible today to get rid of the extra blank paragraph that can be seen in Word output in the second column; this paragraph contains the word instruction to insert a column break.
This works for me.
library(webshot)
flextable(pressure[1:7,])%>% set_caption(caption = "Table 1") %>% save_as_image("tmp1.png")
flextable(cars[1:5,])%>% set_caption(caption = "Table 2") %>% save_as_image("tmp2.png")
knitr::include_graphics(c("tmp1.png", "tmp2.png"))

Is there a way to unify the numbering of tables caption in r markdown to html in r via `kable()` and `htmltable()`?

When I want to print some tables in html report from knitr, sometime I use knitr::kable(), and other times I use htmltable::htmltable.
When I use bookdown::html_document2 in the YAML numbering of tables from kable is automatic. However, it is not for htmltable, and I need to use options(table_counter = TRUE), which generates another numbering mechanism. Is there a way to unify it?
Example:
---
title: "Untitled"
author: "Guilherme"
date: "10/26/2020"
output:
bookdown::html_document2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(table_counter = TRUE)
```
```{r cars}
library(htmlTable)
htmlTable(mtcars[1:5,1:5],
caption = "XX")
```
```{r}
htmlTable(mtcars[1:5,1:5],
caption = "XX")
```
```{r}
library(knitr)
kable(mtcars[1:5,1:5],
caption = "XX")
```
Outputs:
Thanks!

kableExtra generates table code formatted as plain text in final LaTeX file

kableExtra seems to disrupt the proper formatting of kables in LaTeX when the caption contains certain characters.
kableExtra::kable will be formatted properly if no caption is used, or if standard knitr::kable is used.
The following code will yield oddly formatted results if kableExtra is loaded.
---
title: "Mock"
output:
pdf_document:
keep_tex: true
---
```{r header, echo= FALSE, include = FALSE, warning= FALSE}
library(skimr)
library(knitr)
# library(kableExtra)
resumir <- function(var, unit = "", caption = NULL) {
if(is.null(caption)) {caption <- deparse(substitute(var))}
skim_to_wide(var) %>%
mutate_all(as.numeric) %>%
kable(caption = paste0(caption, " (", unit, ")"))
}
mtcars2 <- mtcars %>%
rename("NO_CYL" = 'cyl', "PEAK_PERF" = "mpg")
attach(mtcars2)
```
`r resumir(POWER_HRS, unit = "$hours$")`
I think I know already what's happening but after all the hassle I went through to find the issue I think it's good if this goes up on SO and someone posts an answer (or I will after a bit).
So, to keep it simple, the problem turned out to be having underscores in the caption. The only solution that has worked is to remove them, which is not overly unreasonable.
---
title: "Mock"
output:
pdf_document:
keep_tex: true
---
```{r header, echo= FALSE, include = FALSE, warning= FALSE}
library(knitr)
library(kableExtra)
attach(mtcars)
```
`r kable(cyl, caption = "Cylinder_No.")`
There was a bug report for knitr but knitr currently works fine.

Can you left-justify or bold the table/figure caption for Kable in RMarkdown?

I am using RMarkdown to write reproducible reports, however, I am looking for guidance on how to change the justification on table/figure captions when using Kable?
Also, can you bold or italicize the Table 1: component of the caption?
knitr::kable(head(iris), 'latex', caption = 'Title of table',
booktabs = TRUE) %>%
kableExtra::kable_as_image()
This code will produce a generally nice looking table. However, I want to left-justify the title and bold the text "Table 1:" which automatically precedes my table caption.
Thanks for your help.
You can use the LaTeX captions package to customize your captions. For example, this document
---
output: pdf_document
header-includes:
- \usepackage[justification=raggedright,labelfont=bf,singlelinecheck=false]{caption}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r echo=FALSE}
knitr::kable(head(iris), caption = 'Title of table',
booktabs = TRUE)
```
produces this table output:
Alternatively, if you really want this in a screenshot file, use
library(knitr)
library(kableExtra)
kable(head(iris), format="latex", caption = 'Title of table',
booktabs = TRUE) %>%
as_image(file="~/temp/table.png",
latex_header_includes="\\usepackage[justification=raggedright,labelfont=bf,singlelinecheck=false]{caption}")

Resources