Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

knitr

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

like image 622
msakya Avatar asked Feb 02 '14 16:02

msakya


People also ask

How do I run an R program from the command line?

Running R from the Command LineTo open up the command prompt, just press the windows key and search for cmd. When R is installed, it comes with a utility called Rscript. This allows you to run R commands from the command line.

How do I get command line arguments in R?

Use commandArgs(trailingOnly = TRUE) to obtain a vector of the command-line arguments that a program was run with.

How do I run an R command in bash?

Use Rscript to run R from bash You can run it using Rscript test. r . And even better, if you add an initial shebang line #!/usr/bin/env Rscript in the script above and make it executable with chmod +x test. r , you can directly launch your R script with ./test.


1 Answers

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
like image 108
Yihui Xie Avatar answered Oct 19 '22 00:10

Yihui Xie