【问题标题】:How to use knitr from command line with Rscript and command line argument?如何使用带有 Rscript 和命令行参数的命令行中的 knitr?
【发布时间】:2014-02-02 16:20:56
【问题描述】:

我有一个 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),但可以选择添加参数。

【问题讨论】:

    标签: r knitr


    【解决方案1】:

    我不明白为什么这是不可能的。这里是my_code.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
    

    【讨论】:

    • 请注意,stitch 用于.Rknit 用于.Rnw。这个答案没有错,但我错过了那个微妙之处并陷入了一段时间。
    【解决方案2】:

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

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

    • 你调用knit2pdf的R脚本像这样:m_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"
    

    【讨论】:

    • 我不确定我是否理解正确,但这是否意味着需要创建一个单独的 .Rnw 文件,以及两个文件如何连接?
    • @mshakya 我编辑我的答案以添加更多解释。希望现在很清楚。
    • 哦,这太好了,我想我可以使用它来工作,但是是否可以不必使用 .Rnw 文件,并且可以像使用stitch() 那样运行脚本功能。谢谢
    • 我认为这是我想要的,但可以选择接受参数。 groups.google.com/forum/#!searchin/knitr/…
    • 我不知道这个函数,但我认为你可以像我在这个答案中所做的那样使用它的 env 参数。
    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多