Trying to generate multiple plots and titles sequentially through a loop in an Rmarkdown document. This is the Rmd code.
---
title: "Leaflet"
output: html_document
---
```{r,eval=TRUE,include=FALSE}
library(dplyr)
library(leaflet)
dfr <- data.frame(lat=c(51.517,48.859,50.850),lon=c(-0.074,2.294,4.346),label=c("London","Paris","Brussels"))
```
# As loop
```{r,echo=FALSE,eval=TRUE,results="markup"}
for(i in seq_along(dfr)){
dfr1 <- dfr[i,,drop=FALSE]
knitr::asis_output(paste0("## ",dfr1$label,"\n"))
leaflet(height=450,width="auto") %>%
addTiles(urlTemplate='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>%
addAwesomeMarkers(lat=dfr1$lat, lng=dfr1$lon, label=dfr1$label) %>%
setView(lat=dfr1$lat, lng=dfr1$lon, zoom=10)
}
```
# Individually
```{r,echo=FALSE,eval=TRUE,results="markup"}
dfr1 <- dfr[1,,drop=FALSE]
knitr::asis_output(paste0("## ",dfr1$label,"\n"))
leaflet(height=450,width="auto") %>%
addTiles(urlTemplate='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>%
addAwesomeMarkers(lat=dfr1$lat, lng=dfr1$lon, label=dfr1$label) %>%
setView(lat=dfr1$lat, lng=dfr1$lon, zoom=10)
```
```{r,echo=FALSE,eval=TRUE,results="markup"}
dfr1 <- dfr[2,,drop=FALSE]
knitr::asis_output(paste0("## ",dfr1$label,"\n"))
leaflet(height=450,width="auto") %>%
addTiles(urlTemplate='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>%
addAwesomeMarkers(lat=dfr1$lat, lng=dfr1$lon, label=dfr1$label) %>%
setView(lat=dfr1$lat, lng=dfr1$lon, zoom=10)
```
This is the output.
When run as a loop, it does not display. It works when plotting individually. I am not saving the plots as a list since I have other stuff to print per iteration, for example, the H2 heading as in the above example.
Another example using if.
---
title: "Leaflet"
output: html_document
---
```{r,eval=TRUE,include=FALSE}
library(dplyr)
library(leaflet)
dfr <- data.frame(lat=c(51.517,48.859,50.850),lon=c(-0.074,2.294,4.346),label=c("London","Paris","Brussels"))
```
# If
```{r,echo=FALSE,eval=TRUE,results="asis"}
if("London" %in% dfr$label){
dfr1 <- dfr[dfr$label %in% "London",,drop=FALSE]
cat(paste0("## ",dfr1$label,"\n"))
w <- htmltools::tagList(leaflet(height=450,width="auto") %>%
addTiles(urlTemplate='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>%
addAwesomeMarkers(lat=dfr1$lat, lng=dfr1$lon, label=dfr1$label) %>%
setView(lat=dfr1$lat, lng=dfr1$lon, zoom=10))
cat(as.character(w))
}
```
R 4.1.0
leaflet 2.1.1