Подтвердить что ты не робот

Создание динамических блоков Markdown

В моем наборе данных у меня есть 60 групп, которые я хочу проанализировать, помещая в HTML-отчет, используя R Markdown. Поскольку я хочу применить один и тот же анализ к каждой группе, я надеюсь, что есть способ, которым я могу динамически генерировать кодовые блоки/анализ.

Просто я хочу избежать повторного копирования блока 60 раз.

Я столкнулся с этим этим вопросом, который использует детей в knitr. Я попытался воспроизвести это с помощью набора диафрагмы. В моем примере ниже все, что я хотел сделать, это генерировать три титула H4, по одному для каждого вида.

Стоит отметить, что я не женат на этом подходе, это просто похоже на то, что я ищу.

Вот файлы, которые я использовал:

parent.RMD. Это будет мой "главный" отчет.

Automate Chunks of Analysis in R Markdown 
========================================================


```{r setup, echo=FALSE}
library(knitr)
```


```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
  out = c(out, knit_child('child.Rmd'))
}

`` `

И вот child.Rmd.

#### Species = `r [i]`
4b9b3361

Ответ 1

Попробуйте knit_expand():

Automate Chunks of Analysis in R Markdown 
========================================================

```{r setup, echo=FALSE}
library(knitr)
```

```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
  out = c(out, knit_expand(text='#### Species = {{i}}'))
}
```

`r paste(knit(text = out), collapse = '\n')`

Вы также можете создать файл шаблона, например 'child.rmd', и поместить его в цикл for, чтобы вам не приходилось выполнять сложный анализ в кавычках:

out = c(out, knit_expand('template.rmd'))

Затем введите 'template.rmd':

#### Species = {{i}}

Ответ 2

Принимая решение @sam, я сделал следующую общую функцию. Скажем, у вас есть кадр данных с именем grfDf с объектами графика DiagrammeR в столбце graph. Следующее - все, что вам нужно, чтобы построить все графики в Rmd: r require(DiagrammeR); renderHtmlWidgetList(grfDf$graph, render_graph). См. Код для оговорок.

```
require(knitr)

#' Render a list of htmlWidgets using various tricks
#'
#' @param widgetList A list of htmlWidget objects to be rendered
#' @param renderFunction The function to render individual widgets. It can be either a name
#'   of the rendering function, e.g., "render_graph" in DiagrammeR, or the actual function to
#'   be passed to this call.
#' @return The knitted string. This is to be included in the output by using `r renderHtmlWidgetList(...)`;
#' @details This is a collection of various tricks. See the URL citations in the code.
#'   Note that this code does alliterate global variables starting with "renderHtmlWidgetList_".
#'   You may want to delete them using rm(list = ls(pattern="renderHtmlWidgetList_*")).
#' @examples Inlcude the following in the Rmd directly
#'   `r require(DiagrammeR); renderHtmlWidgetList(grfDf$graph, render_graph)`
#'
#' @export

renderHtmlWidgetList <- function(widgetList, renderFunction){
  # error checking
  stopifnot(is.list(widgetList))
  # handles if the renderFunction is actually a function
  # http://stackoverflow.com/info/10520772/in-r-how-to-get-an-objects-name-after-it-is-sent-to-a-function
  if(is.function(renderFunction)) {
    # convert back to string, because we need to knit it later
    renderFunction <- deparse(substitute(renderFunction))
  }
  stopifnot(is.character(renderFunction) & length(renderFunction)==1)
  stopifnot(exists(renderFunction, mode = "function"))
  # inject global vars; make sure we have a unique global var name
  gVarName<- paste0("renderHtmlWidgetList_", sample(1:10000, 1))
  while (exists(gVarName)) {
    gVarName<- paste0("renderHtmlWidgetList_", sample(1:10000, 1))
  }
  # assigning widgetList to a global temp var
  # http://stackoverflow.com/info/5510966/create-a-variable-name-with-paste-in-r
  assign(gVarName, widgetList, envir = .GlobalEnv)
  # solution from https://gist.github.com/ReportMort/9ccb544a337fd1778179
  out <- NULL
  knitPrefix <- "\n```{r results='asis', cache=FALSE, echo=FALSE}\n\n"
  knitSuffix <- "\n\n```"
  for (i in 1:length(widgetList)) {
    knit_expanded <- paste0(knitPrefix, renderFunction, "(", gVarName, "[[", i, "]])")
    out = c(out, knit_expanded)
  }
  #invisible(out)
  paste(knitr::knit(text = out), collapse = '\n')
}
```