How to extract all code from an RMarkdown (.Rmd) file? - r

How can I extract all the code (chunks) from an RMarkdown (.Rmd) file and dump them into a plain R script?
Basically I wanted to do the complementary operation described in this question, which uses chunk options to pull out just the text (i.e. non-code) portion of the Rmd.
So concretely I would want to go from an Rmd file like the following
---
title: "My RMarkdown Report"
author: "John Appleseed"
date: "19/02/2022"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents.
For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
Some text description here.
```{r cars}
a = 1
print(a)
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Some more comments here.
To an R script containing just the code portions of the above, as the following:
knitr::opts_chunk$set(echo = TRUE)
a = 1
print(a)
summary(cars)
plot(pressure)

You could use knitr::purl, see convert Markdown to R script :
knitr::purl(input = "Report.Rmd", output = "Report.R",documentation = 0)
gives Report.R:
knitr::opts_chunk$set(echo = TRUE)
a = 1
print(a)
summary(cars)
plot(pressure)

Another way is to set the purl hook in your Rmd:
```{r setup, include=FALSE}
knitr::knit_hooks$set(purl = knitr::hook_purl)
knitr::opts_chunk$set(echo = TRUE)
```
Then the R script is generated when you knit. You can exclude some chunks with the chunk option purl = FALSE.

Related

Split Rmarkdown (.Rmd) file into mutiple files (.Rmd)

I made a big Rmarkdown (.Rmd) file that contains only chunks of R codes. I'm wondering if there's a way to automatically generate a (.Rmd) file for every chunk or if I have to manually create a (.Rmd) file for every chunk I have (over 200 chunks).
Let's say I have this (.Rmd) file :
---
title: "Untitled"
output: html_document
date: '2022-08-13'
---
R Markdown
``{r cars}
summary(cars)
``
Including Plots
``{r pressure, echo=FALSE}
plot(pressure)
``
Is there a way to generate automatically a (.Rmd) file for the chuck r cars and another for the chunk r pressure?
Thanks in advance.
A possible solution is to use package parsemd:
library(parsermd)
rmd <- parse_rmd("x.Rmd")
rlabels <- c("cars", "pressure")
yaml <- rmd_select(rmd, has_type("rmd_yaml_list"))
for (i in rlabels)
{
rchunk <- rmd_select(rmd, all_of(i))
sink(paste0(i, ".Rmd"))
cat(as_document(yaml), sep = "\n")
cat(as_document(rchunk), sep = "\n")
sink()
}

R Function for Reading an Image from a URL

I am trying to read a url and get the image from it in order to knit it to a pdf using R Markdown. I've tried using the image_read() function in the magick package, but whenever I knit to my R Markdown pdf, it prints the metadata which I don't want. I tried the strip = TRUE option as well, but it didn't seem to work. Code Below:
library(magick)
url <- "https://a.espncdn.com/combiner/i?img=/i/headshots/mens-college-basketball/players/full/4280043.png"
temp <- image_read(url, strip = TRUE)
temp <- image_scale(temp, "200")
print(temp)
Any help is appreciated!
It works (with a current version of Magick) once you knit your pdf. Try:
---
title: "Magick_test"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## The image
```{r, echo=FALSE, message=FALSE}
library(magick)
url <- "https://a.espncdn.com/combiner/i?img=/i/headshots/mens-college-basketball/players/full/4280043.png"
temp <- image_read(url)
image_scale(temp, "200")
```

When running knit to .Rmd output the chunks are not valid

Problem
When trying to knit an .Rmd containing read_chunk lines from purl scripts into a parent .Rmd, the chunks are not complete and only form code blocks. I want to be able to knit the output file normally.
Code
main.Rmd
---
output: html_document
---
```{r, include=FALSE}
knitr::read_chunk("script_chunk.R")
```
### Print sessionInfo()
```{r, ref.label='script_chunk', eval=FALSE}
```
script_chunk.R
# ---- script_chunk
sessionInfo()
Knitting
When I process this with knit("main.Rmd", "output.Rmd") the following file is generated:
---
output: html_document
---
### Print sessionInfo()
```r
sessionInfo()
```
However, the desired output for the chunk is:
```{r script_chunk}
sessionInfo()
```
When I knit output.Rmd currently, I only get an un-evaluated code block because the chunk is missing the curly braces (and preferably the chunk name).
Workaround
I can use readLines to achieve what I'm after, for example with:
```{r, results='asis', collapse=TRUE, echo=FALSE}
cat("```{r script_chunk}\n")
cat(paste(readLines("script_chunk.R"), "\n", collapse = ""))
cat("```\n")
```
Is there a more elegant way to do this?
There is a slightly more elegant solution:
# main.Rmd
---
output: html_document
---
### Print sessionInfo()
```{r, results="asis", echo = FALSE}
chunk_lines <- knitr::spin(text = readLines("script_chunk.R"), knit = FALSE)
cat(chunk_lines, sep = "\n")
```
But remember that your output, as far as knitr cares, is plain Markdown. knitr can only output to certain formats: LaTeX, Sweave, HTML, Markdown or Jekyll. While your output file has the .Rmd extension, its contents are plain Markdown because that's the default for R Markdown files.
So be aware that all code chunks you want in the output will have to be written as dynamic output. Which could leave you with obfuscated code in main.Rmd.
An alternative I use is with knit_child:
main.Rmd
---
output: html_document
---
```{r, include=FALSE}
out <- knitr::knit_child("script_chunk.Rmd")
```
### Print sessionInfo()
```{r, ref.label='script_chunk'}
paste(out, collapse = "\n")
```
script_chunk.Rmd
```{r script_chunk}
# ---- script_chunk
sessionInfo()
```
When compiled:
---
output: html_document
---
### Print sessionInfo()
```r
# ---- script_chunk
sessionInfo()
```
```
## R version 3.3.3 (2017-03-06)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 16299)
## ... blah blah blah ...
```
Thoughts:
out is a horrible name for this;
I often use it to iterate a single child document (which handles one "thing") over zero or more things, so out can contain concatenated results of multiple calls to knit_child

R inline markdown

I’m using R Markdown in RStudio to create a report that mixes Markdown and R output. I know how to use inline R expressions in the Markdown, but I’m wondering how to do the converse, i.e., use Markdown within the R code. I want to loop through a series of calculations and get Markdown headings for each one. I want headings for formatting purposes (e.g., bold titles etc) and also to be able to specify (sub)sections in the resulting PDF (which is a nice feature of the way RMarkdown handles # and ## etc).
I know I can do the following:
---
title: "test"
output: pdf_document
---
#Section 1
```{r, echo=FALSE}
print(1+1)
```
#Section 2
```{r, echo=FALSE}
print(2+2)
```
#Section 3
```{r, echo=FALSE}
print(3+3)
```
Which gives something looking (roughly) like this:
Section 1
## [1] 2
Section 2
## [1] 4
Section 3
## [1] 6
Is it possible to achieve the same output using something along the lines of this:
---
title: "test2"
output: pdf_document
---
```{r, echo=FALSE}
for (i in 1:3)
{
print(paste("#Section",i))
print(i+i)
}
```
As #scoa pointed out, you have to set the chunk option results='asis'. You should also place two \n both before and after your header.
---
title: "test"
output: pdf_document
---
```{r, echo=FALSE, results='asis'}
for (i in 1:3) {
cat(paste0("\n\n# Section", i, "\n\n"))
print(i+i)
cat("\n\n\\newpage")
}
```
As a more general answer, it could be useful to a look at the markdownreports package that parses markdown code (and output) from your R variables.

How to include external R file with RMarkdown? [duplicate]

It's fairly trivial to load external R scripts as per this R Sweave example:
<<external-code, cache=FALSE>>=
read_chunk('foo-bar.R')
#
Can the same be done for R Markdown?
Yes.
Put this at the top of your R Markdown file:
```{r setup, echo=FALSE}
opts_chunk$set(echo = FALSE, cache=FALSE)
read_chunk('../src/your_code.R')
```
Delimit your code with the following hints for knitr (just like #yihui does in the example):
## #knitr part1
plot(c(1,2,3),c(1,2,3))
## #knitr part2
plot(c(1,2,3),c(1,2,3))
In your R Markdown file, you can now have the snippets evaluated in-line:
Title
=====
Foo bar baz...
```{r part1}
```
More foo...
```{r part2}
```

Resources