我试图生成一个flexdashboard,从循环内创建每个页面,每个生成的页面都包含dygraph
(尽管任何HTML小部件应该表现相同)。
我看了很多,似乎可以使用rmarkdown
生成cat("title")
条评论(根据此处的解决方案:generate markdown comments within for loop)。
另一方面,如果您使用htmltools::tagList()
(根据此处的解决方案:For loop over dygraph does not work in R),HTML小部件的行为很好。
我没有工作代码可以分享,但这广泛地说明了我希望实现的目标:
for (i in 1:ncol(downloadedData)){
fund_NAVS <- downloadedData[,i] #this is an xts object
fund_NAVS <- fund_NAVS[!is.na(fund_NAVS)]
cat("pageTitle")
cat("===================================== \n")
cat("Row\n")
cat("------------------------------------- \n")
cat("### Page title")
dygraph(fund_NAVS)
}
答案 0 :(得分:2)
我已经能够使用pander::pandoc.header
使其部分工作。但是,让内容(图表和HTML对象)实际显示在最终的HTML文件中是一个不同的故事。
---
output:
flexdashboard::flex_dashboard:
orientation: columns
source: embed
vertical_layout: fill
---
```{r results='asis'}
library(pander)
pages <- 5
cols <- 2
sections <- 3
for (p in 1:pages) {
pandoc.header(paste("Page", p), level = 1)
for (c in 1:cols) {
pandoc.header(paste("Column", c), level = 2)
for (s in 1:sections) {
pandoc.header(paste("Section", s), level = 3)
cat("hi")
pandoc.p("")
}
}
}
```
答案 1 :(得分:2)
我能够通过显式构建r块然后用r paste(knitr::knit(text = out))
内联编织来自动生成内容。这个惊人的代码行在SO post中找到。
就我而言,我想制作一系列图表,每个图表都有一个单独的标签,内容不同。每个图表都相似但有很多(大约15个),我不想复制/粘贴所有单独的块。
Here is a gist you can download一个更简单的例子。 (代码也在下面,但请注意我在每个块之前添加\
,以便将其呈现为单个代码块,因此在运行之前删除\
。)我构建了构建图形的功能要复杂得多,但R块的概念可以转发到包含htmlwidgets作为元素的任何列表对象。
---
title: "Loop to Auto Build Tabs Containing htmlwidgets"
output: flexdashboard::flex_dashboard
---
\```{r setup, echo =FALSE, eval = TRUE}
library(tidyverse)
library(flexdashboard)
library(highcharter)
labels <- mtcars %>% names # these will serve as labels for each tab
# create a bunch of random, nonsensical line graphs
hcs <- purrr::map(.x = mtcars, ~highcharter::hchart(mtcars, y = .x, type = 'line')) %>%
setNames(labels) # assign names to each element to use later as tab titles
\```
Page
====================
Column {.tabset .tabset-fade}
-----------------------------
<!-- loop to build each tabs (in flexdashboard syntax) -->
<!-- each element of the list object `out` is a single tab written in rmarkdown -->
<!-- you can see this running the next chunk and typing `cat(out[[1]])` -->
\```{r, echo = FALSE, eval = TRUE}
out <- lapply(seq_along(hcs), function(i) {
a1 <- knitr::knit_expand(text = sprintf("### %s\n", names(hcs)[i])) # tab header, auto extracts names of `hcs`
a2 <- knitr::knit_expand(text = "\n```{r}") # start r chunk
a3 <- knitr::knit_expand(text = sprintf("\nhcs[[%d]]", i)) # extract graphs by "writing" out `hcs[[1]]`, `hcs[[2]]` etc. to be rendered later
a4 <- knitr::knit_expand(text = "\n```\n") # end r chunk
paste(a1, a2, a3, a4, collapse = '\n') # collapse together all lines with newline separator
})
\```
<!-- As I mentioned in the SO post, I don't quite understand why it has to be -->
<!-- 'r paste(knitr::knit(...)' vs just 'r knitr::knit(...)' but hey, it works -->
`r paste(knitr::knit(text = paste(out, collapse = '\n')))`