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!
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.
Related
Basically i want to build a random multiple choice question generator with R Markdown. For this task there need to be equations in the code chunks of the markdown.
The following works like a charm and gives the equation "greekbeta = 1"
---
title: "test"
author: "me"
output:
word_document: default
---
```{r eval=TRUE, echo=FALSE,results = "asis"}
"$\beta = 1$"
```
In contrast, this will not work when some other math symbol is used, for example:
---
title: "test"
author: "me"
output:
word_document: default
---
```{r eval=TRUE, echo=FALSE,results = "asis"}
"$\sum_{n=1}^{\infty}$"
```
After pressing knit, an error occurs (unfortunately the error message is in german, basically this: "'\s' is an unknown escape-sequence within the string starting with "$/s"").
I am very puzzled by this, especially because for example \frac{1}{2} works, but \hat{x} does not. Equations in the "normal" markdown text are no problem at all. But for my task, the equations have to be in the code chunk sections.
Does someone has a workaround for this problem? I tried using "$\hat{x}$" or even "$$\hat{x}$", but the error message is still the same.
I am using pandoc 2.11.4, R 4.1.0 and knitr 1.33
Use cat() and escape the escapes.
---
title: "test"
author: "me"
output:
word_document: default
---
```{r eval=TRUE, echo=FALSE,results = "asis"}
cat("$\\beta = 1$", '\n\n')
cat("$a^2+b^2 = c^2$", '\n\n')
cat("$\\sum_{n=1}^{\\infty}x_i$", '\n\n')
```
I'd like to rmarkdown::render a R document without indicating the yaml options within the document itself.
Ideally that could be an argument on rmarkdown::render or knitr::spin like what you can do to pass params (see the Rmarkdown reference book). Typically I'd like author, date and the output options too.
I think this is possible because spining the following document without specifying anything I get the following output (so there must be a template of default args that I can hopefully change)
As an example, how could I do to render a document that would give me the same output as say the below (but of course without specifying the yaml in the document ie no yaml whatsoever in the document)
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
pdf_document:
toc: true
highlight: zenburn
---
#' # Title
Hello world
#+ one_plus_one
1 + 1
You can pass yaml options as parameters too. For example:
---
params:
title: "add title"
author: "add author"
output: pdf_document
title: "`r params$title`"
author: "`r params$author`"
---
This is my document text.
Then, in a separate R script:
rmarkdown::render("my_doc.rmd",
params=list(title="My title",
author="eipi10"))
You could cat a sink into a tempfile.
xxx <- "
#' # Title
Hello world
#+ one_plus_one
1 + 1
"
tmp <- tempfile()
sink(tmp)
cat("
---
title: 'Sample Document'
output:
html_document:
toc: true
theme: united
pdf_document:
toc: true
highlight: zenburn
---", xxx)
sink()
w.d <- getwd()
rmarkdown::render(tmp, output_file=paste(w.d, "myfile", sep="/"))
I'm trying to use params. My problem is that I want to assign to previous_working_day some default day using library bizdays.
title: "MyDocument"
author: "SomePerson"
date: !r Sys.Date()
output: html_document
params:
previous_working_day: !r adjust.previous(Sys.Date()-1, cal)
---
```{r}
library(bizdays)
```
During kniting with parameters in GUI instead of date I have string
adjust.previous(Sys.Date()-1, cal).
The reason is that there isn't loaded library earlier. But when I tried add library on the beginnig I get error. So this way that don't work:
```{r}
library(bizdays)
```
---
title: "MyDocument"
author: "SomePerson"
date: !r Sys.Date()
output: html_document
params:
previous_working_day: !r adjust.previous(Sys.Date()-1, cal)
---
How I can deal with it to give previous_working_day some value when I need to use other library earlier?
I am new to R markdown and knitr and haven't found the answer to this question:
I have R scripts where I've written functions and have assigned data to position 1 (.GlobalEnv). How do I access my data and run my functions within R markdown and generate the .html file with knitr?
Here's a trivial example. In a script file I generate:
some.x.data<-1:10
some.y.data<-1:10
toy.fn<-function(){
tot<-some.x.data + some.y.data
tot
}
toy.fn() works in the script file.
My R markdown file contains:
---
title: "trivial test"
author: "me"
date: "July 9, 2015"
output: html_document
---
```{r}
plot(some.x.data, some.y.data)
toy.fn()
```
When I click knit HTML, I get the following error:
Error in plot(some.x.data, some.y.data) : object 'some.x.data' not found
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> plot
Thanks
RStudio opens a new R session to knit() your Rmd file, so the objects in .GlobalEnv will not be available to that session (they are two separate sessions), so when you are knitring HTML there is not way to know what some.x.data, some.y.data and toy.fn is.
Either you need to recreate them in your Rmd file. If you don't want any output just do:
```{r, echo = FALSE, message = FALSE}
some.x.data<-1:10
some.y.data<-1:10
toy.fn<-function(){
tot<-some.x.data + some.y.data
tot
}
```
Full Rmd:
---
title: "trivial test"
author: "me"
date: "July 9, 2015"
output: html_document
---
```{r, echo = FALSE, message = FALSE}
some.x.data<-1:10
some.y.data<-1:10
toy.fn<-function(){
tot<-some.x.data + some.y.data
tot
}
```
```{r}
plot(some.x.data, some.y.data)
toy.fn()
```
Or
knit manually by yourself: library(knitr); knit('your_file.Rmd')
I found a really nice trick (link) to a function of knitr, where you can save your output html into an output folder and under a different filename.
The only thing you have to head to the header is the following:
title: "analysis"
author: "Me"
date: "`r format(Sys.time(), '%d %B, %Y, %H:%M')`"
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile,
encoding=encoding,
output_file=file.path(dirname(inputFile), out_dir, 'analysis.html')) })
output:
html_document:
number_sections: yes
toc: yes
This works on my Mac 'sometimes' very well, but sometimes it has problems to find the out_dir variable...
I first thought about executing the chunks first, so the variable is set... But this didn't solved the problem...
I also restarted R session and this didn't helped.
The last step was closing R, saving the workspace and after reopening R and loading workspace it works like a charm again.
I could not find the original post, where somebody recommended this trick...
EXACT WORKFLOW TO REPRODUCE
open new project, name it test in a new folder
create a r markdown document
change the header to:
---
title: "Untitled"
author: "Me"
date: "`r format(Sys.time(), '%d %B, %Y, %H:%M')`"
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile,
encoding=encoding,
output_file=file.path(dirname(inputFile), out_dir, 'analysis.html')) })
output:
html_document:
number_sections: yes
toc: yes
---
```{r write quant output files}
out_dir <- 'test'
if(!file.exists(out_dir)) {
dir.create(out_dir)
}
```
save the document as test.Rmd
click the knit button (html is now removed from the options of the button)
This will fail!
Close the project!
Click on save environment!
Open the Project and click knit!
Everything works.
execute rm(list=ls()) everything works afterwards again
You could try setting the out_dir variable in the function you are giving knit to render:
knit: (function(inputFile, encoding) {
out_dir <- 'test';
rmarkdown::render(inputFile,
encoding=encoding,
output_file=file.path(dirname(inputFile), out_dir, 'analysis.html')) })
I found it cumbersome to write the output-file name so I swapped the output_file to output_dir argument but kept the rest of the code. In this way my Rmarkdown is still knitted into a subdirectory but with the inputFile name. Also, if the directory does not exist, it is created
---
title: "title"
author: "gordon freeman"
date: "`r Sys.Date()`"
knit: (function(inputFile, encoding) {
out_dir <- "reports";
rmarkdown::render(inputFile,
encoding=encoding,
output_dir=file.path(dirname(inputFile), out_dir))})
---