0

Following on from this question... I am not sure where to set knitr option if I want to output a separate file of R code. The following does not provide the expected additional .R files in my working directory.

---
output: ioslides_presentation
---

```{r setup, include=FALSE}
library("knitr"); purl("myfile.rmd")
#library("knitr"); knit("test_tangle.Rmd", tangle = TRUE)
#opts_knit$set(tangle=TRUE)
```

## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```

but an error message...

Quitting from lines 6-7 (myfile.rmd) 
Error in readLines(if (is.character(input2)) { : 
  cannot open the connection
Calls: <Anonymous> ... withVisible -> eval -> eval -> purl -> knit ->     readLines
Execution halted
6
  • 1
    have you tried library("knitr"); purl("myfile.rmd") ? Commented Apr 17, 2015 at 12:46
  • 1
    knit("test_tangle.Rmd", tangle = TRUE) works for me. Commented Apr 17, 2015 at 12:47
  • @BenBolker Both suggestions give an error message? I created the file using File | New File | R Markdown... | Presentation and then did a Save As before hitting the Knit HTML button Commented Apr 17, 2015 at 13:04
  • 1
    I think @RomanLuštrik and I are both suggesting that you try running our commands from the console. Commented Apr 17, 2015 at 13:19
  • @BenBolker. I see, I was fixated on trying to do it within the .Rmd file and hence oblivious to your approaches. Many thanks. Commented Apr 17, 2015 at 13:30

1 Answer 1

1

I recommend you to use the hook_purl function instead. The function purl() (or equivalently, knit(tangle = TRUE)) may fail to work in certain cases, and the hook function hook_purl() is more reliable. See ?hook_purl for more information.

---
output: ioslides_presentation
---

```{r setup, include=FALSE}
library("knitr")
knit_hooks$set(purl = hook_purl)
```

## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```

Then as you knit the document, the R script will be automatically generated.

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

1 Comment

Thanks @Yihui. Just what I wanted. Awesome!

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.