Reputation: 9821
I have an R code my_code.R
which takes in an argument a file test.txt
. I can use:
Rscript -e my_code.R test.txt
and run the script, but i want to use stitch() from knitR to generate the report of the script in pdf/tex.
I have trolled around stack overflow and used following suggestions, but didn't get any results:
Rscript -e "library(knitr);knit('my_code.R "-args arg1=test.txt" ')"
Rscript -e "knitr::stitch('my_code.R "-args arg1=test.txt"')"
Here is another similar discussion on what i want (link), but with option for adding argument(s).
Upvotes: 12
Views: 6665
Reputation: 630
Try rmarkdown::render()
to get the (e. g. PDF) directly created from your .R file. Parameters can also be passed. https://bookdown.org/yihui/rmarkdown-cookbook/rmarkdown-render.html
Upvotes: 0
Reputation: 30194
I do not see why this is not possible. Here is my_code.R
:
commandArgs(TRUE)
And I simply run
Rscript -e "library(knitr); stitch('my_code.R')" --args foo bar whatever=blabla
I get the output
It seems you did not use double quotes correctly in your original attempt. It should be
Rscript -e "library(knitr); stitch('my_code.R')" --args arg1=test.txt
Upvotes: 9
Reputation: 121618
You can use knit2pdf
and pass parameters to the report using its envir
argument.
In other words , the solution is to create 2 seperates files an :
knit2pdf
like this : m_code.R
m_code_report.Rnw
This script contains all you R code. The idea, is to create an environment variable "params" , where you put all parameters need to be displayed/presented.
library(knitr)
library(markdown)
ff <- commandArgs(TRUE)[1]
params <- new.env()
e$ff <- ff
## here I pass all the parameters to the report
## I assume that the report and the code R in the same location
## the result pdf also will be in the same location , otherwise you can set
## paths as you like
knit2pdf('m_code_report.Rnw',envir=params) report
The report display resulted using variables contained in the environment "params".
\documentclass{article}
\begin{document}
<<>>=
summary(ff)
@
\end{document}
Then you call the Rscript using Rscript for example like this:
Rscript m_code.R "cars"
Upvotes: 0