Empty all code chunk contents in Rmd file

I'm developing a set of R Markdown files with coding exercises for live coding during class. At the moment, I'm developing all of the code chunks to run. But I would like to automatically generate a version of the file without the code chunk contents (so we can code it in class). That is, I'm initially creating the files as the 'answer key' but would like to easily create an identical version without the code. Is there an easy way to empty the contents from all of the code chunks? Like the opposite of knitr::purl()--but instead of extracting and only keeping the code, it extracts and removes the code, leaving the rest of the Rmd file. Note that I want the code removed from the Rmd file not just the output (e.g., with echo=FALSE), because we will be working directly with the live coding Rmd file. Any thoughts are appreciated!

I haven't checked for a pre-fab way to do this but can see to things to try

  1. Replace each chunk with print("Left as an exercise to the student"), which preserves the location of the chunk and provides dummy output for whatever other tests are required.

  2. bash script using sed or another tool to remove the entire chunk, remove lines between opening and closing backticks or substitute the message above.

Thanks for the suggestions @technocrat . I'm looking to stay within R. So maybe I just need some fancy regular expression magic?

Looks like this might work:

gsub("```\\{r\\}.+?```", "```\\{r\\}\n\n```", text)

Well, the previous code only works if there are no code chunk options. Here's a more general function that should work for code chunks that include options:

empty_chunk <- function(x) {
  x <- gsub("\\{r .+?\\}", "\\{r\\}", x)
  x <- gsub("```\\{r\\}.+?```", "```\\{r\\}\n\n```", x)

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.