3

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?

Community
  • 1
  • 1
gregmacfarlane
  • 2,121
  • 3
  • 24
  • 53

1 Answers1

2

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(), ...)

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98