Get and execute the sample code from the package function R as a code block in R-markdown

I want to extract the sample code from a package Rand run it in a file rmarkdownautomatically.

I can extract the code using the function utils::exampleas follows.

example("geom_histogram", package = "ggplot2", ask = F,
         prompt.prefix = "", give.lines = TRUE)[-(1:5)]

I tried using chunk options results="asis"as follows, but the result is listed as code output, not a piece of code.

```{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("```")
```

I would like to have the code as a block of code, and the output is the same as in http://ggplot2.tidyverse.org/reference/geom_histogram.html . How to achieve this?

+4
source share
1 answer

Updated answer:

You can create a function to extract the code and use it as an argument codein the chunk option.

# 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") , :

enter image description here


:

(foo.R) code chunk.

(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") :

enter image description here

, :

```{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")}
```
+5

Source: https://habr.com/ru/post/1695106/


All Articles