如何使用 knitr 在 RMD 中循环渲染 leaflet-maps

How to render leaflet-maps in loops in RMDs with knitr

我目前正在努力让 knitr 渲染我的传单地图,从 collection 中获取以在渲染的 RMD html-output 中正确显示。我已经意识到循环遍历 collections 并使用 RMD/knitr 生成图形输出时的一些潜在问题,但我仍然无法弄清楚如何使我的示例适用于 leaflet-maps .

可重现的工作示例 (Test_1.Rmd):

---
title: "test1"
author: "phabee"
date: "22 Mai 2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Title 1

```{r, fig.show='asis', echo=FALSE, results='asis'}
for (i in 1:4) {
    cat("### Plot Number ", i, "\n")
    plot(1,1)
    # use plot.new() here to force rendering of potential plot-duplicates
    plot.new()
    cat("\n\n")
}
```

上面的示例按预期呈现(至少在添加 plot.new() 之后,这是我从 Freedomtowin 中学到的 here)。但是当我尝试用 leaflet-maps 做同样的事情时,它根本不起作用。没有渲染单个地图:

可重现的失败示例 (Test_2.Rmd)

---
title: "test2"
author: "phabee"
date: "22 Mai 2018"
output: html_document
---

```{r setup, include=FALSE}
library(leaflet)
knitr::opts_chunk$set(echo = TRUE)
```

## Title 1

```{r, fig.show='asis', echo=FALSE, results='asis'}
for (i in 1:4) {
  cat("### Map Number ", i, "\n")
  leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")  
  cat("\n")
}
```

我希望第二个 Rmd 渲染 4 次相同的地图,显示不同的标题 ("Plot Number 1-4")。但是输出根本不渲染任何地图。输出如下所示:

检查生成的 html-output 输出后,可以看出根本没有渲染任何东西,它不仅仅是一个 visibility-issue:

但是,当我直接通过 'highlighting' 代码评估第二个 Rmd 中的 leaflet-section 并点击 ctrl-Enter 时,地图按预期呈现:

我已经试过了

没有任何效果。有人知道这里的线索吗?

您需要将内容放入 tagList 中,并从块中打印该列表。这仅使用 fig.showresults 的默认设置;它还使用 htmltools::h3() 函数将标题直接变成 HTML 标题,而不是使用 Markdown ### 标记。 (您可能需要 h2h4。)

---
title: "test3"
output: html_document
---

```{r setup, include=FALSE}
library(leaflet)
library(htmltools)
knitr::opts_chunk$set(echo = TRUE)
```

## Title 1

```{r echo=FALSE}
html <- list()
for (i in 1:4) {
  html <- c(html, 
            list(h3(paste0("Map Number ", i)),
                 leaflet() %>%
                 addTiles() %>%  # Add default OpenStreetMap map tiles
                 addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")  
                 )
            )
}
tagList(html)
```