Create sections through a loop with knitr

你离开我真会死。 提交于 2019-12-03 17:26:06

It seems like I found a way!

The whole idea is to pass what would be typed by hand as a string inside of knit(text=the_string) used in inline code.

So the function basically pastes a bunch of strings together, with a bit of substitute magic to have a function that feels like it's part of the apply family.

  • Parameter depth decides how many # you want.

  • Parameter options contains the chunk options, as a vector.

A vector shouldn't be able to contain logical and characters together but here it doesn't matter as it will all be coerced to character anyway, so c(echo= FALSE, results="hide") is fine.

I expect that it's easy to break but seems to work fine when treated gently.

---
title: "test"
output: html_document
---

```{r setup, include = FALSE}
library(knitr)    
mdapply <- function(X, FUN, depth, options=""){
  FUN       <- as.character(substitute(FUN))
  list_name <- as.character(substitute(X))
  if(options != "")
    options <- paste(",",names(options),"=",options,collapse="")
  build_chunk <- function(nm)
  {
    paste0(
      paste0(rep("#",depth), collapse=""),
      " ",
      nm,
      "\n\n```{r", options, "}\n",
      FUN,
      "(", list_name, "[['", nm, "']])\n```")
  }      
  parts <- sapply(names(X), build_chunk)
  whole <- paste(parts, collapse="\n\n")
  knit(text=whole)
  }
```

```{r code}
my_list   <- list(foo = 1:3, bar = 4:7, baz = 8:12)
```

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