3

I have text files that I want to display in an RMD document as unevaluated code, and hidden behind a code-folding button. I'm using this method and this method to include my text files, but I want to automate the process of pulling these files in.

This solution works, but instead of having dozens of lines like this:

    # Create an External Script
    writeLines("# A Sample R Script", "external.R")

    # Then include the R script in an Rmd document
    <details>
    ```{r, code = readLines('external.R')}
    ```
    </details>
    <details>
    ```{r, code = readLines('external.R')}
    ```
    </details>
    <details>
    ```{r, code = readLines('external.R')}
    ```
    </details>

Is there a way I can use cat or paste to wrap this into a function, where the only thing that is changing is the external script that I'm using?

# Define the function
my_fn <- function(script_path){
  paste0("<details>\n```{r, code = readLines(", script_path, ")}\n```\</details>"
}

# Then use in Rmd
my_fn("external.R")
my_fn("external.R")
my_fn("external.R")
kputschko
  • 766
  • 1
  • 7
  • 21
  • After much trial and error, I'm finding that R Markdown really does not like putting ``` in quotes, and I can't find a way around that. I can get the code chunk to appear by replacing ` with \x60, but the code is not evaluated in RMD. – kputschko Feb 28 '22 at 16:07
  • 1
    This would be really helpful to create a shortcut function for inserting figures, where most of the options lie within the { } brackets, see https://stackoverflow.com/questions/63665513/how-to-add-subfigure-in-r-markdown-bookdown – Jost Aug 23 '22 at 21:57

0 Answers0