sourcing and displaying R source code in R Markdown without executing - r

I am writing a book in R Markdown. I saved a lot of code in separate .R files. For didactical purpose I need to show the whole file's contents without actually running it.
e.g., I would like that
r my_r_chunk
source("./code/mycodefile.R")
```
would be rendered displaying the whole content of mycodefile.R without actually executing it.

Check out ?knitr::read_chunk
First, assign a label to the script using the syntax ## ---- your_label ---- by placing it in the first line of the script which is called foo.R
foo.r
## ---- your_label ----
print("Hello World")
1:10
After assigning the script a label, you can then read_chunk the script in an uncached chunk. Finally you reference the contents in a subsequent (cached) chunk using the eval = FALSE chunk option.
your_Rmd_file.Rmd
---
output: pdf_document
---
```{r cache=FALSE, echo = FALSE}
library(knitr)
read_chunk('foo.R')
```
```{r your_label, cache = TRUE, eval=FALSE}
```

Related

Display Block of R Code in Knitr With Evaluation Turned Off

I am writing a document with fairly resource intensive R code. I want to prevent execution of one block of R code in knitr which is giving me document timeout error in Overleaf.
In R studio, this can be done using eval = FALSE. I want to recreate this in knitr. So far, the only way I have found is to suppress errors using <<setup, include=FALSE, cache=FALSE>>= muffleError <- function(x,options) {} but it only works on the entire document.
I specifically want to prevent evaluation but show the R code.
Is this what you want to do, or have I misunderstood? The eval = FALSE is in one code chunk and the second chunk still plots.
---
title: "A Test Knit"
output: html_document
---
## Show code but don't run
```{r, eval = FALSE}
summary(cars)
```
## Run and render plot
```{r}
plot(pressure)
```

Run R markdown (.Rmd) from inside other R script to produce HTML

As the example, if you create a new R markdown file and save it as 'test'. Can one then run or deploy this test.Rmd file from within a normal R script. The purpose being to generate the output in HTML, without having to open the .Rmd file.
I'm hoping to create one master file to do this for many markdown files in one go; which would save considerable time as you then don't have to open many markdown files and wait for each one to complete.
You are looking for rmarkdown::render().
Contents of "test.Rmd"
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. 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>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
Contents of script.R
# provided test.Rmd is in the working directory
rmarkdown::render("test.Rmd")
A Way to Render Multiple Rmd
cwd_rmd_files <- list.files(pattern = ".Rmd$")
lapply(cwd_rmd_files, rmarkdown::render)
Thanks the-mad-statter, your answer was very helpful. The issue I faced, required me to prepare markdown dynamically. By adapting your code, that's easily possible:
Contents of "test_dyn.rmd"
---
title: "Untitled"
output: html_document
---
The chunk below adds formatted text, based on your inputs.
```{r text, echo=FALSE, results="asis"}
cat(text)
```
The chunk below uses your input in as code.
```{r results}
y
```
Contents of "script_dyn.r"
in_text <- c("**Test 1**", "*Test 2*")
in_y <- 1:2
lapply(1:2, function(x) {
text <- in_text[[x]]
y <- in_y[[x]]
rmarkdown::render(input = "test_dyn.rmd", output_file = paste0("test", x))
})
Like this you can create files with different text and different variables values in your code.

Is it possible to create a self-rendering Rmarkdown document?

For typical R scripts the shebang syntax can be used to run the code within. With a file file.R
#!/usr/bin/env Rscript
<some R code here>
Running ./file.R will execute the code.
But can somehow the same be done with R-markdown? So that with a file named file.Rmd:
#!/usr/bin/env <some command>
<some markdown>
<some R code here>
<some markdown again>
Running ./file.Rmd would produce file.md?
You can treat an Rmd file as an Rscript. For instance, assume that your Rmd file looks like this
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. 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>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
You can then prepend the following code to that Rmd file
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
The trick here is q("no"). This line terminates the R session, and, thus, whatever written after it will be ignored. Such an effect also means high flexibility for coding because you can write almost any valid R code before that q("no"). The code above simply creates another temporary Rmd file with the same content as what is after q("no"). Then, we rmarkdown::render that temporary file and dump the output to the current directory.
The complete Rmd file looks like this
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. 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>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Disclaimer: I do not know much about Linux, nor do I have a Linux machine with R installed available to test my answer. Let me know if this does not work properly. If this inspires someone to write a better answer, I'll happily delete this one.
Let me approach this backwards:
To knit a document, we need to call rmarkdown::render().
To run this command from a command line, we can use RScript -e "rmarkdown::render('document.Rmd')", see e.g. here.
Probably you do not want to hardcode the path to Rscript but use a shebang like #!/usr/bin/env Rscript instead.
The problem with this approach is that it does not allow to pass arguments to Rscript.
I therefore propose to use a "wrapper" in the shebang that is responsible for calling Rscript.
With the name of the RMD file as argument, the required R code becomes rmarkdown::render(commandArgs(trailingOnly=TRUE)[1]).
Step by step:
Create the wraper (in any directory that is in your $PATH) and make it executable:
touch KnitWrapper.sh
chmod +x KnitWrapper.sh
Write the following to KnitWrapper.sh:
#!/usr/bin/env bash
Rscript -e "rmarkdown::render(commandArgs(trailingOnly=TRUE)[1])" $1
Make sure Rscript is in your $PATH. If you update R, update your $PATH accordingly.
In your RMD file, add the shebang #!/usr/bin/env KnitWrapper.sh.
Make your RMD file executable and run it:
chmod +x yourDocument.Rmd
./yourDocument.Rmd
Unfortunately, the above is largely untested. Let me know if it does not work, so I can either fix or delete this answer.

How can I print the function description of an R package to Rmarkdown instead of terminal?

Using R markdown and trying to write a small document for the group I'm working in. I wanted to be able to print a functions description directly into the Rmarkdown document I'm writing. For example if I wanted the description for the function "cor" I would use
?cor
And this prints the description in the terminal I'm working on. Now using
print(?cor)
Or
dummy <- ?cor
print(dummy)
doesn't print the description to the Rmarkdown file, but instead again prints in inside the terminal and hangs, until the user exits at which point the RMarkdown pdf is generated. Unfortunately there is no sign of it within the pdf.
How can I make R print this to Rmardkdown and not the terminal?
What you need is the printr package. Make sure you install it before using the example Rmarkdown code below (i.e. run install.packages('printr') first), but here's an example of how to include a help file in an Rmarkdown created PDF:
---
title: "SO"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Printing Help
```{r}
library(printr)
help(sum)
```

Is it possible to source multiple external chunk from a file in Knitr/ Rmarkdown?

I have an R-script file script.r as,
## ---- Chunk-1 ----------
x <- rnorm(1000)
## ---- Chunk-2 ----------
hist(x)
Now in my rmarkdown document doc.rmd, I can read the script.r file as,
knitr::read_chunk("script.r")
I can execute both the chunks as follows,
```{r Chunk-1}
```
```{r Chunk-2}
```
Is there anyway, I can execute Chunk-1 and Chunk-2 together. In my real situation, I have lots of chunks, and I want them separate in script file but I need some of them execute together in the Rmd file. I am wondering if there is any easier approach rather than repeating blank chunk block.
Maybe I am missing something but I do not see the goal of using your script.r file as chunks. When looking at your example, if you want to execute your script.r file in your Rmd file, you can directly use source('script.r').
Except if you want to execute some chunks based on conditions for instance. In that aim, do you know that you can call a complete external Rmd file as a child document ?
Your child-script.Rmd:
```{r Chunk-1}
x <- rnorm(1000)
```
```{r Chunk-2}
hist(x)
```
Your main Rmd script:
Some markdown text
```{Call_child, child='./child-script.Rmd'}
```
Some other markdown text

Resources