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

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.

Related

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.

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)
```

Can't generate plotly interactive plots in Rmarkdown report

I have an Rmarkdown document with a plot made with plotly and would like to generate an html file. It works when I click on Knit to HTML in Rstudio, but not when I run the following on the command line:
Rscript -e "require(knitr)" -e "require(markdown)" -e "knit('Untitled.Rmd', out='report.md')" -e "markdownToHTML('report.md', 'report.html')"
After this, I have a report.html file which contains the plot generated with plotly, but it is not interactive.
Does anyone know how to make it interactive with the command line?
Thanks
This is the code, btw:
---
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)
```
## Including Plots
You can also embed plots, for example:
```{r pressure_ggplot, echo=FALSE}
library(ggplot2)
library(plotly)
ggplot(pressure,aes(temperature,pressure))+geom_point(size=10,color='red')
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
```{r pressure_plotly, echo=FALSE}
g<-ggplot(pressure,aes(temperature,pressure))+geom_point(size=10,color='red')
ggplotly(g)
```
```{r}
sessionInfo()
```
Try:
Rscript -e "library(knitr); library(rmarkdown); rmarkdown::render('untitled.Rmd', output_file='report.html')"
Reasoning: knit seems to default to markdown output, and doesn't retain HTMLwidgets in the rendered markdown. Thus, when converting, you end up with missing files (you can see these errors if you remove echo=FALSE from the code block openings.
rmarkdown::render([...]) renders cleanly to HTML, avoiding the issues mentioned above. If you wish to specify the output format, you can do so using the output_format argument.

sourcing and displaying R source code in R Markdown without executing

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}
```

Remove Markdown Default Code

In RStudio, whenever I make a new Markdown it always has default code. How do I remove it?
Here's the code that shows up.
```{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.
Every time, when creating a Rmd file, Rstudio will open a Rmd template:
https://github.com/rstudio/rstudio/blob/822e558c7a274de464f992f69e3acee2fde5ab04/src/cpp/session/modules/SessionRMarkdown.R
# given a path to a folder on disk, return information about the R Markdown
# template in that folder.
.rs.addFunction("getTemplateDetails", function(path) {
# check for required files
templateYaml <- file.path(path, "template.yaml")
skeletonPath <- file.path(path, "skeleton")
if (!file.exists(templateYaml))
return(NULL)
if (!file.exists(file.path(skeletonPath, "skeleton.Rmd")))
return(NULL)
# load template details from YAML
templateDetails <- yaml::yaml.load_file(templateYaml)
# enforce create_dir if there are multiple files in /skeleton/
if (length(list.files(skeletonPath)) > 1)
templateDetails$create_dir <- TRUE
templateDetails
})
Hence the simplest solution would be:
go to xxx\RStudio\resources\templates folder, where your
Rstudio installed
open r_markdown_v2.Rmd file, and delete
everthing
save it
Now, everytime, when you open a rmarkdown, you can have just the yaml part.

Resources