How to convert R script to Rmd or Quarto file ?

Hi All,
Is this possible ? I have got R script and do not want copy and paste everything into new file and chunks.
Is it a way to convert R script to Rmd or Quarto file with code and results of that code ?
The other way around is to use purl() function, but how to do it starting from R script ?

If you do not need to display the code when the Rmd/Quarto document is exported, you could just source the R script in a code chunk near the top of the document.

I need to display code as well.

If you want to display it all in one place, it's a single copy and paste. If you want to play chunks in different places, and do not already have the non-R text of the document written, you could open your .R script in a text editor, surround each chunk with ```{r} and ```, and paste the whole thing into an empty (other than headers) Rmd/Quarto document ... but I'm not sure that's any easier than just copy/paste chunk by chunk.

I do this periodically, and I always have to split the code into code chunks. Usually it is because I'm converting a script to a recurring report for clients, and the flow of the report text makes it easier to have code chunks throughout generating figures that can be hyperlinked to the text. Once you get a flow going you can do it pretty quickly.

I think you're looking for the knitr::spin function: 3.3 Render an R script to a report | R Markdown Cookbook

3 Likes