Last active
May 4, 2022 15:42
-
-
Save blahah/5f5232ba217d07a7e37e to your computer and use it in GitHub Desktop.
Print marked-up, unevaluated code from another file using Rmarkdown / knitr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
title: "test" | |
author: "Richard Smith-Unna" | |
date: "21 May 2015" | |
output: html_document | |
--- | |
Demo of reading an R file and dumping it raw into the HTML produced by knitr from RMarkdown, to get syntax highlighting. | |
Put the code you want to display in `import.R`. | |
Two ways to do it... | |
```{r} | |
# first load the code | |
sourcecode <- paste(readLines("import.R"), collapse="\n") | |
``` | |
This block loads the code from an external variable, doesn't evaluate it, and just prints it marked up as though it were a normal block. | |
```{r eval=FALSE, code=sourcecode} | |
``` | |
This block prints the code directly to the resulting markdown file, with the code block tags added, using `cat()` to avoid line numbers. | |
```{r results='asis', echo=FALSE} | |
cat(paste("```r", sourcecode, "```", sep="\n")) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment