15

I'm running a markdown report from command line via:

R -e "rmarkdown::render('ReportUSV1.Rmd')"

This report was done in R studio and the top looks like

---
title: "My Title"
author: "My Name"
date: "July 14, 2015"
output: 
  html_document:
   css: ./css/customStyles.css
---


```{r, echo=FALSE, message=FALSE}

load(path\to\my\data)
```

What I want is to be able to pass in the title along with a file path into the shell command so that it generates me the raw report and the result is a different filename.html.

Thanks!

1 Answer 1

23

A few ways to do it.

You can use the backtick-R chunk in your YAML and specify the variables before executing render:

---
title: "`r thetitle`"
author: "`r theauthor`"
date: "July 14, 2015"
---

foo bar.

Then:

R -e "thetitle='My title'; theauthor='me'; rmarkdown::render('test.rmd')"

Or you can use commandArgs() directly in the RMD and feed them in after --args:

---
title: "`r commandArgs(trailingOnly=T)[1]`"
author: "`r commandArgs(trailingOnly=T)[2]`"
date: "July 14, 2015"
---

foo bar.

Then:

 R -e "rmarkdown::render('test.rmd')" --args "thetitle" "me"

Here if you do named args R -e ... --args --name='the title', your commandArgs(trailingOnly=T)[1] is the string "--name=foo" - it's not very smart.

In either case I guess you would want some sort of error checking/default checking. I usually make a compile-script, e.g.

# compile.r
args <- commandArgs(trailingOnly=T)
# do some sort of processing/error checking
#  e.g. you could investigate the optparse/getopt packages which
#   allow for much more sophisticated arguments e.g. named ones.
thetitle <- ...
theauthor <- ...
rmarkdown::render('test.rmd')

And then run R compile.r --args ... supplying the arguments in whichever format I've written my script to handle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.