23

I really like using knitr in Rstudio and have been using it to write markdown presentations and data analysis. I want to use the same code and results in a paper and want to convert the code chunks in Rmd file ```{r} to the chunks of Rnw file << >>= @.

This allows using the same document and code written for presentation for the main paper as well.

Is there a way of converting between code chunks of markdown and Rnw files ?

or the entire file itself as apart from the difference in syntax of code chunks, they are quite similar in the markup (converting the text to latex is easy with say pandoc)

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
Anusha
  • 1,716
  • 2
  • 23
  • 27

1 Answers1

10

Instead of converting the whole document, you can just externalize your R code so it can be shared across different documents; see http://yihui.name/knitr/demo/externalization/

Once you have read_chunk('Rcode.r'), you can use ```{r label} in your Rmd and <<label>>= in your Rnw document, where label comes from the line ## @knitr label in the R script.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • The idea of keeping the code separate from the main file is good.Just in case if I need to quickly convert the Rmd file to Rnw or vice-versa, is it a possibility? – Anusha Jul 22 '12 at 08:16
  • 1
    That sounds wonderful, but does not make much sense to me: https://github.com/yihui/knitr/issues/322 It is easy to convert ```{r} to `<<>>=`, but what about the rest of texts? You have to consider converting markdown to LaTeX (vice versa), and pandoc has already done an unbeatable job of that. – Yihui Xie Jul 22 '12 at 16:09
  • It seems you are working on this as knitExtra. I did convert the document from markdown to latex using pandoc as mentioned in the question. The task of converting code chunks using regex or replacing strings seemed to be tedious and error prone. Would you please tell the easy way to convert chunks markup? – Anusha Jul 22 '12 at 16:17
  • Thanks for making knitr. Writing documents has become much better now. – Anusha Jul 22 '12 at 16:26
  • 4
    I don't actually plan to work on knitrExtra. Converting code chunks using regex is the only way to go, and it should not be too bad. I mean it is a much smaller challenge compared to converting other texts, so I recommend you to compile Rmd to md, and start conversion from md to other formats, instead of converting the source document. The other way is to use `spin()`: you can write a single R script and convert it to either Rnw or Rmd or other formats; see the second section of this page: http://yihui.name/knitr/demo/stitch/ Again this doesn't solve the problem of converting other texts. – Yihui Xie Jul 22 '12 at 17:15
  • +1 for the workarounds. Will see if this conversion gets incorporated in pandoc or some other tool. :) – Anusha Jul 22 '12 at 18:58
  • Is there any easy way to handle citation? So far I used `@Xie` in .Rmd and `\citep{Xie}` in .Rnw? – Matt Bannert Aug 04 '15 at 10:38