我想从R包中提取示例代码并自动在rmarkdown文件中运行它. 我能够使用函数utils :: example提取代码,如下所示. example("geom_histogram", package = "ggplot2", ask = F, prompt.prefix = "", give.lines = TRUE)[-(1:5)
我能够使用函数utils :: example提取代码,如下所示.
example("geom_histogram", package = "ggplot2", ask = F, prompt.prefix = "", give.lines = TRUE)[-(1:5)]
我尝试使用chunk options results =“asis”如下,但结果是作为代码输出而不是代码块给出的.
```{r,echo = FALSE, results="asis"} cat("```{r}") library(ggplot2) cat(paste(example("geom_histogram", package = "ggplot2", ask = F, prompt.prefix = "", give.lines = TRUE)[-(1:5)], collapse = "\n")) cat("```") ```
我希望将代码作为代码块,输出与http://ggplot2.tidyverse.org/reference/geom_histogram.html相同.如何实现这一目标?
更新的答案:您可以创建一个函数来提取代码并将其用作块选项中的代码参数.
# Function saved in functions.R file getCode <- function(myFunction, myPackage) { example(myFunction, myPackage, ask = FALSE, character.only = TRUE, prompt.prefix = "", give.lines = TRUE)[-(1:5)] }
你的Rmd(myFile.Rmd)应该是这样的:
06001
Knit Rmd with:knitr :: knit2html(“myFile.Rmd”),结果如下:
上一个答案:
将提取的代码写入虚拟文件(foo.R)并将其用作块选项中的代码参数.
示例文件(myFile.Rmd):
>第一块:加载测试库
>第二个块:提取示例并将其保存到文件中
>第三个块:运行提取的代码
06002
使用knitr :: knit2html(“myFile.Rmd”)编织文件,得到如下结果:
我们还可以删除硬编码变量以获得更灵活的输出:
06003