Q: Create leaflet map in for loop in rmarkdown html

Deadly 提交于 2019-12-05 06:39:47

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!