Updated answer:
You can create a function to extract the code and use it as an argument codein the chunk option.
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 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") :

, :
```{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")}
```