msakya
msakya

Reputation: 9821

How to use knitr from command line with Rscript and command line argument?

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

Answers (3)

Jaleks
Jaleks

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

Yihui Xie
Yihui Xie

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

knitr stitch() 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

agstudy
agstudy

Reputation: 121618

You can use knit2pdfand pass parameters to the report using its envir argument.

In other words , the solution is to create 2 seperates files an :

  • R script where you call knit2pdf like this : m_code.R
  • a markdown report file (.Rnw,.Rmd) : m_code_report.Rnw

m_code.R

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

m_code_report.Rnw

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

Related Questions