问:在rmarkdown html中的for循环中创建传单地图 [英] Q: Create leaflet map in for loop in rmarkdown html
问题描述
我正在尝试在rmarkdown文件中创建带有for循环的传单地图.
I am trying to create a leaflet map with a for-loop in an rmarkdown file.
这是一个最小的示例:
---
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))
}
```
此代码没有任何输出.单独运行Leaflet命令(并将i
替换为整数)时,它可以工作.我也尝试了打印命令,但这也不起作用.
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.
现在,您可以创建一个传单,并在循环外添加addTiles,并在循环中添加addMarkers,但实际上您根本不需要for循环,只需一次添加所有标记.
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))
在rpubs上查看正在工作的.rmd
See the working .rmd here at rpubs
http://rpubs.com/dhawalkapil/quakesdata
R块工作
```{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))
```
具有多个地图
让我们在年份上添加一列.然后,我们将不得不使用htmltools::tagList
,如@NicE所述.分割年份"并使用lapply
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)}))
```
在上面的相同网址中查看更新rpubs.
See the update rpubs in the same url above.
这篇关于问:在rmarkdown html中的for循环中创建传单地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!