Is there any way to run R markdown script from command line?

I want to run a Rmd script from command line using something like this:

Rscript script.Rmd

But this throws an error because the 'Rscript' command does not understand the R markdown syntax. I don't want to 'render' the R markdown. What I want is just to be able to run only the code chunks included in the Rmd file from the command line. Is there any way to do this without copy-pasting all the code chunks into a new separate script file?

rmarkdown is designed to render a Rmd file's texts and executing its code both into a single output stream. AFAIK, there's no way within the package to render only the chunk output.

If you are on a *nix there's a scripting way of doing this that I can outline. I haven't had to use windows long enough that I have no idea whether the same ideas apply.

Given script.Rmd, write a sed command to extract the chunks, stripping them of their triple backticks , | pipe it to the littler pipe-friendly R binary, see the results on stdout, tee or pipe to file.

I don't think you need to go this far :wink:
There is already a function in knitr to extract all the R code from a Rmd file. See ?knitr::purl. It uses the tangle = TRUE in knitr.

Here is an example of how to generate a R script from Rmd's chunks.

temp_rmd <- tempfile(fileext = ".Rmd")
xfun::write_utf8(c(
  "---",
  "title: test",
  "output: html_document",
  "---",
  "",
  "# a title",
  "",
  "```{r iris-dim}",
  "dim(iris)",
  "```",
  ""
), temp_rmd)

cat(xfun::read_utf8(temp_rmd), sep = "\n")
#> ---
#> title: test
#> output: html_document
#> ---
#> 
#> # a title
#> 
#> ```{r iris-dim}
#> dim(iris)
#> ```


temp_r <- tempfile(fileext = ".R")
knitr::purl(temp_rmd, output = temp_r)
#> processing file: C:\Users\chris\AppData\Local\Temp\RtmpcTXwV2\filec52c50c83709.Rmd
#> output file: C:\Users\chris\AppData\Local\Temp\RtmpcTXwV2\filec52c5b727f17.R
#> [1] "C:\\Users\\chris\\AppData\\Local\\Temp\\RtmpcTXwV2\\filec52c5b727f17.R"
cat(xfun::read_utf8(temp_r), sep = "\n")
#> ## ----iris-dim-----------------------------------------------------------------
#> dim(iris)

Created on 2020-04-07 by the reprex package (v0.3.0.9001)

The currently in writing Rmarkdown cookbook has a chapter on this feature:

Historically, there was a knitr example on this

You also have on example of what purl can be useful

You can then execute the script.

Hope it helps

6 Likes

This is exactly what I needed. Thank you!

One thing to note for future viewers:

If you put eval=FALSE option in the code chunk, that code chunk is entirely commented out in the knitr::purl() output.

2 Likes

Yes purl result in a Rscript that is the same the result as if you executed the chunk by rendering. That is why eval = FALSE is commented out.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.