I want to have an R chunk in RMarkdown that includes code from an external file.
I want to include the file, rather than embed its contents directly, because the external file contains code that is shared between various projects and scripts, and I want to be sure that each program uses the most recent version. The code = ...
chunk option is made for this.
The following method works fine if I knit the whole document. However, if I try to run the individual chunks inside Rstudio (as required during development) I get an error "Error in readLines(include_file) : object 'include_file' not found"
.
How do I get this to work so I can run chunks from within Rstudio?
Reproducible example:
First create some include files
write_lines("x = 1", 'include_1.r')
write_lines("x = 2", 'include_2.r')
write_lines("x = 3", 'include_3.r')
write_lines("x = 4", 'include_4.r')
Then put the following into a .Rmd file
---
title: "Untitled"
output: html_document
---
```{r setup}
knitr::opts_chunk$set(echo = TRUE)
include_file = list.files(pattern = '^include_.+[Rr]$')
include_file = include_file[which.max(file.info(include_file)$mtime)]
```
I want to embed an R code from a file like this:
```{r, code = readLines(include_file)}
```
Then use the objects from the include file
```{r}
print(x)
```
This is what the output looks like when I knit the whole document