Q: Create a booklet map in a for loop in rmarkdown html

I am trying to create a flyer map with a for loop in the 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 am not getting any output with this code. When you run only the leaflet command (and replace 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?

+5
source share
2 answers

you complicated it a little.

See that you need to create a booklet and apply markers on top of it, choosing longitudes and latitudes from unique stations.

But here you create flyers in a loop. As well as adding tiles to the loop, which is the main problem.

Now you can create a flyer and addTiles from a loop and addMarkers in a loop, but you really don't need a for loop and add all the markers at a time.

First select a dataset using unique stations

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

Create a booklet and add markers using the above filter data as data

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

See working .rmd here, rpubs

http://rpubs.com/dhawalkapil/quakesdata

Worker 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 cards

Add a column of years. Then we will have to use htmltools::tagList , as explained by @NicE. Separate "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 rpubs updates in the same url above.

+6
source

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 an argument, so I changed your for loop to lapply .

+3
source

Source: https://habr.com/ru/post/1243130/


All Articles