2015-07-16 4 views
5

sto correndo un rapporto Markdown da linea di comando tramite:passare parametri da linea di comando nel documento R Markdown

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

Questo rapporto è stato fatto in studio R e la parte superiore si presenta come

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

Quello che voglio è essere in grado di passare nel titolo insieme a un percorso file nel comando shell in modo che mi generi il rapporto grezzo e il risultato sia un file filename.html differente.

Grazie!

risposta

9

Alcuni modi per farlo.

È possibile utilizzare il pezzo backtick-R in YAML e specificare le variabili prima di eseguire il rendering:

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

foo bar. 

Poi:

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

Oppure si può utilizzare commandArgs() direttamente nella RMD e dei mangimi li dopo --args:

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

foo bar. 

Quindi :

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

qui se nominato args R -e ... --args --name='the title', il vostro commandArgs(trailingOnly=T)[1] è la stringa "--name = foo" - non è molto intelligente.

In entrambi i casi, suppongo che vorreste una sorta di controllo degli errori/controllo predefinito. Generalmente faccio uno script di compilazione, ad es.

# 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') 

e quindi eseguire R compile.r --args ... fornendo gli argomenti in qualsiasi formato che ho scritto il mio script da gestire.