This question shows how to loop over/apply leaflet objects within a markdown file. I'd like to do a similar thing, though I'd like to add additional markdown content.
---
title: "Test"
output: html_document
---
```{r setup, echo=T,results='asis'}
library(leaflet)
library(dplyr) ### !!! uses development version with tidyeval !!!
library(htmltools)
##Add A Random Year Column
data(quakes)
quakes <- tbl_df(quakes) %>%
mutate(year = sample(2008:2010, n(), replace=TRUE))
```
```{r maps, echo=T,results='asis'}
createMaps <- function(year){
cat(paste("###", year, "\n"))
leaflet(quakes %>% filter(year == !!year)) %>%
addTiles() %>%
addMarkers(
lng = ~long,
lat = ~lat,
popup = ~as.character(mag))
cat("\n\n")
}
htmltools::tagList(lapply(as.list(2008:2010), function(x) createMaps(x) ))
```
If I leave out the cat statements in the createMaps function, this code prints all three maps. If I put in the cat statements, I get the markdown, but no maps. Any way to combine both types of element?
The problem is, that your cat statements are being evaluated, before lapply returns its result list.
Delete the cat statements, change your createMaps function to
createMaps <- function(year){
mymap <- leaflet(quakes %>% filter(year == !!year)) %>%
addTiles() %>%
addMarkers(
lng = ~long,
lat = ~lat,
popup = ~as.character(mag))
return(list(tags$h1(year), mymap))
}
and change tags$h1() to whatever size of header you want (tags$h2(), ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With