I am currently fighting trying to get knitr to render my leaflet maps, taken from a collection to appear correctly in a rendered RMD html-output. I'm already aware about some potential problems when looping throug collections and generating graphical output with RMD/knitr, but still I can't figure out, how to make my example work for leaflet-maps.
Reproducible working example (Test_1.Rmd):
---
title: "test1"
author: "phabee"
date: "22 Mai 2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Title 1
```{r, fig.show='asis', echo=FALSE, results='asis'}
for (i in 1:4) {
cat("### Plot Number ", i, "\n")
plot(1,1)
# use plot.new() here to force rendering of potential plot-duplicates
plot.new()
cat("\n\n")
}
```
The above example renders as expected (at least after adding plot.new(), which I've learned here from Freedomtowin). But when I try to do the same with leaflet-maps, it doesn't work at all. No single map is being rendered:
Reproducible failing example (Test_2.Rmd)
---
title: "test2"
author: "phabee"
date: "22 Mai 2018"
output: html_document
---
```{r setup, include=FALSE}
library(leaflet)
knitr::opts_chunk$set(echo = TRUE)
```
## Title 1
```{r, fig.show='asis', echo=FALSE, results='asis'}
for (i in 1:4) {
cat("### Map Number ", i, "\n")
leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
cat("\n")
}
```
I would expect the second Rmd to render 4 times the same map, showing different titles ("Plot Number 1-4"). But the output doesn't render any map at all. The output looks as follows:
After inspecting the generated html-output the output, it can be seen that there is nothing rendered at all and it's not just a visibility-issue:
However, when I evaluate the leaflet-section within the 2nd Rmd directly by 'highlighting' the code and hitting ctrl-Enter, the map renders as expected:
I already tried to
- convert the leaflet-statement to an assignment statement
- introduce cat() or print() commands to force map-output
- play around with additional newline-characters '\n' before and/or after the map output section
- fiddle around with the 'asis' directives from fig.show or results
without any effect. Does anyone have a clue here?