Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q: Create leaflet map in for loop in rmarkdown html

I am trying to create a leaflet map with a for-loop in an rmarkdown file.

Here is a minimal example:

---
title: "Test"
output: html_document
---

```{r quakes, echo=F}
data(quakes)
library(leaflet)

for (i in c(10:20))
{
leaflet(data = quakes[1:5 & quakes$stations == i,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag))
}
```

I do not get any output with this code. When running the leaflet command alone (and replacing the i with an integer) it works. I also tried the print command, but that didn't work either.

Any idea how I can do this?

like image 966
Afoy Avatar asked Feb 16 '16 11:02

Afoy


2 Answers

you have complicated it a little bit.

See you have to create a leaflet and apply markers on top of it by selecting longitudes and latitudes from unique stations.

But here you are creating leaflets in a loop. And also adding tiles in a loop which is the main problem.

Now you can create a leaflet and addTiles out of the loop and addMarkers in a loop but you dont actually need a for loop at all and add all the markers in one go.

First, Select Data Sets by Unique Stations

distinct_by_stations<-distinct(quakes,stations) #dplyr is needed for 'distinct'

Create leaflet and add markers using the above filter data set as data

leaflet(data = distinct_by_stations) %>% addTiles() %>% addMarkers(~long,~lat,popup=~as.character(mag))

See the working .rmd here at rpubs

http://rpubs.com/dhawalkapil/quakesdata

Working R Chunk

```{r quakes, echo=T}
data(quakes)
library(leaflet)
library(dplyr)

distinct_by_stations<-distinct(quakes,stations)
leaflet(data = distinct_by_stations) %>% addTiles() %>% addMarkers(~long,~lat,popup=~as.character(mag))
```

With Multiple Maps

Let's add a column on years. Then we will have to use htmltools::tagList as explained by @NicE. Split on 'year' and use lapply

```{r quakes, echo=T,results='asis'}
data(quakes)
library(leaflet)
library(dplyr)
library(htmltools)
##Add A Random Year Column
quakes$year=sample(2006:2015,length(quakes),replace=TRUE)
createMaps<-function(x){
        distinct_by_stations<-distinct(x,stations)
        lflt<-leaflet(data = distinct_by_stations) %>% addTiles() %>% addMarkers(~long,~lat,popup=~as.character(mag))
}

htmltools::tagList(lapply(split(quakes,quakes$year),function(x){createMaps(x)}))
```

See the update rpubs in the same url above.

like image 63
Dhawal Kapil Avatar answered Nov 11 '22 04:11

Dhawal Kapil


You can use tagList from htmltools:

library(htmltools)
maps <- lapply(c(unique(quakes$stations)),function(x){
    leaflet(data = quakes[1:5 & quakes$stations == x,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag))    
})

tagList(maps)

It takes a list as argument so I changed your for loop to a lapply.

like image 25
NicE Avatar answered Nov 11 '22 03:11

NicE