Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rmarkdown/knitr: How to format function output as code?

Here's a rmarkdown snippet:

#Is this even achievable?
```{r echo = FALSE, comment = ""}
install.package(mvbutils)
library(mvbutils)
make.usage.section("paste", env=asNamespace('base'))
```

As expected this (when knitred in RStudio to pdf) prints something along the lines of

paste(..., sep = " ", collapse = NULL)

Note the absence of the leading ##, by default appended to function output but in this example switched off using the comment flag. Is it possible to further adapt the representation of that output such that it equates (code highlighting and all) to the output of:

```{r eval = FALSE}
paste(..., sep = " ", collapse = NULL)
```

I'm writing a howto and this would make life REALLY easy.

like image 904
balin Avatar asked May 26 '26 09:05

balin


1 Answers

You can assign code to a chunk via the code option. Then formatR::usage() returns the code to show the usage of a function. Putting them together:

```{r, code=formatR::usage('paste'), eval=FALSE}
```
like image 197
Yihui Xie Avatar answered May 30 '26 05:05

Yihui Xie