Let's say I have a dataset with several variables, which I want to explore by plotting their distributions e.g. in a bar diagram each. I create a Rmarkdown report and automate this plotting in a vectorized function. Easy enough:
---
title: "Doc title"
output: html_notebook
---
```{r setup}
library(tidyverse, magrittr)
opts_knit$set(root.dir = ROOT_DIR)
opts_chunk$set(results = 'asis', warning = FALSE)
```
```{r dataset}
set.seed(303574)
dataset <- tibble(
var_1 = sample.int(4, 20, replace = TRUE),
var_2 = sample.int(7, 20, replace = TRUE)
)
```
# Histograms
```{r plot}
dataset %>% iwalk(
~{
dataset %$% qplot(.x, xlab = .y, geom = "bar") %>% print()
}
)
```
When I knit this document I get the expected result. Now, I want to create a section by adding a title for each variable, thus separating the plots in different sections (in this case, with a tab for each variable).
This is what I would expect to render the output I intend:
---
title: "Doc title"
output: html_notebook
---
```{r setup}
library(tidyverse, magrittr)
opts_knit$set(root.dir = ROOT_DIR)
opts_chunk$set(results = 'asis', warning = FALSE)
```
```{r dataset}
set.seed(303574)
dataset <- tibble(
var_1 = sample.int(4, 20, replace = TRUE),
var_2 = sample.int(7, 20, replace = TRUE)
)
```
# Histograms {.tabset}
```{r plot, results='asis'}
dataset %>% iwalk(
~{
paste0("## ", .y) %>% cat(fill = TRUE)
dataset %$% qplot(.x, xlab = .y, geom = "bar") %>% print()
}
)
```
However, what is happening is that both titles are rendered before any of the plots. As a result, I have one empty tab per variable, except for the last one, where all the plots are rendered altogether (in this minimal example, one empty tab and another one with the two plots, instead of a plot per tab).
How would I force knitr
to alternate the rendering of the text and the plots?
I tried with a for
loop, i.e.:
for (var in dataset %>% colnames()) {
paste("##", var) %>% cat(fill = TRUE)
qplot(dataset[[var]], xlab = var, geom = "bar") %>% print()
}
But this didn't work either.
Thank you so much!
P.S.: Please note this question is similar to this one; however, the difference is that I'm trying to add the automatically rendered titles here.
Update (2020-05-06):
As it turns out, this only happens when the output is a notebook (i.e., html_notebook
); when rendered to an html_document
, the plots are placed properly and it's not an issue anymore.