我想从R
包中提取示例代码,并自动在rmarkdown
文件中运行。
我能够使用函数utils::example
提取代码,如下所示。
example("geom_histogram", package = "ggplot2", ask = F,
prompt.prefix = "", give.lines = TRUE)[-(1:5)]
我尝试使用块选项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中的相同。怎么做到这一点?
答案 0 :(得分:5)
更新回答:
您可以创建一个函数来提取代码并将其用作块选项中的code
参数。
# 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
)应如下所示:
```{r, meta, include = FALSE} myPackage <- "ggplot2" myFunction <- "geom_histogram" source("functions.R") ``` ```{r, intro, echo = FALSE, results = "asis"} cat("#", myPackage, "\n") cat("##", myFunction, "\n") library(myPackage, character.only = TRUE) ``` ```{r, runCode, code = getCode(myFunction, myPackage)} ```
使用Rmd
编织knitr::knit2html("myFile.Rmd")
,得到如下结果:
上一个回答:
将提取的代码写入虚拟文件(foo.R
)并将其用作块选项中的code
参数。
示例文件(myFile.Rmd
):
```{r, meta, include = FALSE} library(ggplot2) ``` ```{r, getCode, include = FALSE} code <- example("geom_histogram", package = "ggplot2", ask = FALSE, prompt.prefix = "", give.lines = TRUE)[-(1:5)] write.table(code, "foo.R", quote = FALSE, row.names = FALSE, col.names = FALSE) ``` ```{r, runCode, code = readLines("foo.R")} ```
使用knitr::knit2html("myFile.Rmd")
编织文件,得到如下结果:
我们还可以删除硬编码变量以获得更灵活的输出:
```{r, meta, include = FALSE} myPackage <- "ggplot2" myFunction <- "geom_histogram" library(myPackage, character.only = TRUE) ``` ```{r, getCode, include = FALSE} code <- example(myFunction, myPackage, ask = FALSE, character.only = TRUE, prompt.prefix = "", give.lines = TRUE)[-(1:5)] write.table(code, "foo.R", quote = FALSE, row.names = FALSE, col.names = FALSE) ``` ```{r, intro, echo = FALSE, results = "asis"} cat("#", myPackage, "\n") cat("##", myFunction, "\n") ``` ```{r, runCode, code = readLines("foo.R")} ```