Search code examples
rknitrrstudiosweave

Using R Markdown chunks in R Sweave(Knitr)


I have a R Markdown file that has my notes and chunks of code. I now want to write a R Sweave(Knitr) document to publish a paper using those chunks. I do not want to cut and paste the chunks, I rather call them directly. That way if I update the chunks, I don't have to do it in two places. It seems like it would be simple enough, but I can not figure it out. My code is as follows, test.rmd is my mark down document, foo is the chunk in the rmd file.

Test.rnw

 <<Setup>>===
 read_chunk('test.rmd') 
 @
 <<foo>>==
 @

Test.rmd

```{r foo, echo=TRUE}
   print(summary(cars))
```

I would expect a summary of cars to be displayed in the output of the compilation of test.rnw into a PDF. But I don't. Any help is greatly appreciated.


Solution

  • read_chunk reads chunks from r script so call purl before read_chunk:

    <<Setup>>=
    knit_patterns$set(all_patterns[["md"]])
    purl("test.Rmd")
    knit_patterns$set(all_patterns[["rnw"]])
    read_chunk("test.R")
    @
    
    <<foo>>=
    @