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?
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.
distinct_by_stations<-distinct(quakes,stations) #dplyr is needed for 'distinct'
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))
```
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.
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
.
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