Can I wrap markdown and R code chunks into a function?

Viewed 65

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")
0 Answers
Related