Home > other >  How to reproducibly include R code in Word documents with Rmarkdown?
How to reproducibly include R code in Word documents with Rmarkdown?

Time:08-30

I have some R code in a package. I don't want to copy that code, but I want to display it in a pretty way in Word with syntax highlighting without any manual steps.

I looked at styler::style_text in combination of capture.output and that looks nice in the browser, but all the formatting is lost when knitting to Word. Is there some way to preserve it? I'm thinking the best thing would be to have Word native styling but the next best (acceptable) thing would be to somehow render the output to an image and include that. Has anyone done these things to document their code in a report?

show_code = function (fun) {
  stopifnot(is.function(fun))
  out = capture.output(fun)
  n = length(out)
  without_bytecode_and_env_lines = -1*c(n-1, n)
  code = paste(out[without_bytecode_and_env_lines], collapse = "\n")
  styler::style_text(code)
}

CodePudding user response:

I believe you are trying to use syntax highlighting on the output of show_code and to do that, you simply need to use the options comment="" and class.output="r" and syntax highlighting will apply to the output.


---
title: "Source Code highlighting"
output: 
  word_document:
    highlight: kate
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

```{r echo=FALSE}
show_code = function (fun) {
  stopifnot(is.function(fun))
  out = capture.output(fun)
  n = length(out)
  without_bytecode_and_env_lines = c(n-1, n)
  code = paste0(out[-without_bytecode_and_env_lines], collapse = "\n")
  styler::style_text(code)
}
```

### The source code for `lm`

```{r comment='', echo=FALSE, class.output = "r"}
show_code(lm)
```


syntax highlighting in Output


  • Related