3

I am using knitr to create a set of lecture slides for a class using R. I would like to create a separate "companion file" that contains just has the R code (corresponding to the slides), so that students can execute the R code by cutting and pasting from the companion file.

For example, in the .Rmd file:

``` {r ....}
plot(x,y)
```

Then there would be a text file with:

plot(x,y)

But, have such a file be automatically produced from the .Rmd file?

Even better if the .Rmd file has such tags:

``` {r basic.plot ....}
plot(x,y)
```

Then, text file has:

# basic.plot
plot(x,y)

Can this be accomplished using knitr?

1
  • 2
    Yes. Add tangle = TRUE when you are running knit and all code chunks will automatically be saved in an R file. Commented Dec 31, 2013 at 18:38

1 Answer 1

6

Yes, this is possible. What you're trying to do is called tangling, and it comes from the world of literate programming.

The knit function supports a tangle option that should be set to TRUE if you want to extract source code.

Sign up to request clarification or add additional context in comments.

2 Comments

or just purl(), for short.
Thank you everyone. The tangle=TRUE option produced the desired output. Thank you both for provided the solution and the background explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.