如何使用命令行中的knitr与Rscript和命令行参数?

时间:2014-02-02 16:20:57

标签: r knitr

我有一个R代码my_code.R,它接受​​一个文件test.txt的参数。我可以用:

   Rscript -e my_code.R test.txt 

并运行脚本,但我想使用knitR中的stitch()生成pdf / tex中的脚本报告。

我已经控制了堆栈溢出并使用了以下建议,但没有得到任何结果:

   Rscript -e "library(knitr);knit('my_code.R "-args arg1=test.txt" ')"
   Rscript -e "knitr::stitch('my_code.R "-args arg1=test.txt"')"

这是关于我想要什么(link)的另一个类似的讨论,但是有添加参数的选项。

2 个答案:

答案 0 :(得分:7)

我不明白为什么这是不可能的。这是my_code.R

commandArgs(TRUE)

我只是跑

Rscript -e "library(knitr); stitch('my_code.R')" --args foo bar whatever=blabla

我得到了输出

knitr stitch() output

您原来的尝试中似乎没有正确使用双引号。它应该是

Rscript -e "library(knitr); stitch('my_code.R')" --args arg1=test.txt

答案 1 :(得分:0)

您可以使用knit2pdf并使用其envir参数将参数传递给报告。

换句话说,解决方案是创建2个单独的文件:

  • R脚本,您可以这样调用knit2pdfm_code.R
  • 降价报告文件(.Rnw,.Rmd):m_code_report.Rnw

m_code.R

此脚本包含所有R代码。这个想法是创建一个环境变量“params”,你需要显示/显示所有参数。

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

使用环境“params”中包含的变量生成报告。

\documentclass{article}
\begin{document}
<<>>=
summary(ff)
@
\end{document}

然后使用Rscript调用Rscript,例如:

Rscript m_code.R "cars"