如何通过Rscript和命令行参数从命令行使用knitr?
我有一个R代码如何通过Rscript和命令行参数从命令行使用knitr?,r,knitr,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
,它接受一个参数文件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"')"
下面是关于我想要什么()的另一个类似的讨论,但有添加参数的选项。您可以使用
knit2pdf
并使用其envir
参数将参数传递给报表
换句话说,解决方案是创建两个单独的文件:
- 调用
的R脚本如下:knit2pdf
m_code.R
- 降价报告文件(.Rnw,.Rmd):
m\u code\u report.Rnw
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
我不明白为什么这是不可能的。这是我的代码.R:
commandArgs(TRUE)
我只是跑
Rscript -e "library(knitr); stitch('my_code.R')" --args foo bar whatever=blabla
我得到输出
看来您在最初的尝试中没有正确使用双引号。应该是
Rscript -e "library(knitr); stitch('my_code.R')" --args arg1=test.txt
我不确定我是否理解正确,但这是否意味着需要创建一个单独的.Rnw文件,以及两个文件是如何连接的?@mshakya我编辑我的答案以添加更多解释。希望现在一切都清楚了。哦,这太好了,我想我用它工作了,但是有没有可能不用使用.Rnw文件,并且可以像使用stitch()函数一样运行脚本。谢谢,我想这是我想要的,但我可以选择接受这些论点。我不知道这个函数,但我想你可以像我在这个答案中所做的那样使用它的env参数。请注意,
stitch
用于.R
,而knit
用于.Rnw
。这个答案并没有错,但我忽略了这个微妙之处,于是我在一个兔子洞里呆了一段时间。
Rscript -e "library(knitr); stitch('my_code.R')" --args foo bar whatever=blabla
Rscript -e "library(knitr); stitch('my_code.R')" --args arg1=test.txt