在命令行中运行Rmarkdown时是否可以提供参数?

时间:2017-07-14 14:04:52

标签: r knitr r-markdown

我正在尝试根据模板创建不同的报告集。

  1. 是否可以从命令行运行此报告,而不是通过RStudio(编织PDF)运行?

  2. 我有一个名为app的向量,我为每个应用运行此报告并输出值。从命令行运行此报告时,是否可以通过命令行选项提供应用程序?我不想在Rmarkdown中使用应用程序,而是需要知道我是否可以将其作为参数提供?

  3. 每次运行时,pdf文件名都是一样的。如何更改此设置以使pdf文件名与应用程序值相同?

    title: "Application Report"
    
    date: "July 13th, 2017"
    header-includes:
       - \usepackage{longtable}
       - \usepackage[table]{xcolor}
       - \usepackage{colortbl}
       - \usepackage[utf8]{inputenc}
    output:
      pdf_document:
        fig_caption: yes
        fig_height: 6
        fig_width: 7
        highlight: zenburn
        number_sections: yes
        toc: yes
        toc_depth: 3
    keep_tex: yes
    tables: yes
    fontsize: 15
    ---
    
    ```{r message=FALSE, results = 'asis', echo=FALSE, warning=FALSE, fig.width=12, fig.height=10}
    
    app<-c("Web","DB)
    
    
    for (i in app){
    
        cat(paste("# ",app, " - Application","\n"))
    }
    

1 个答案:

答案 0 :(得分:4)

简短回答:

  1. 示例:我将使用两个文件和一个命令行示例。使用makefile或扩展knit-application-report.R脚本将简化您的工作流程。

    第一个文件:application-report.Rmd我已经从您的示例文件中简化了此帖子。重要的是要定义变量app。此变量将在报告标题中使用,并可在报告的其他位置使用。

    ---
    title: "`r app` Report"
    date: "`r date()`"
    output: pdf_document
    ---
    
    This is the report for the `r app` application.
    
    ```{r}
    # do stuff
    ```
    

    文件2:knit-application-report.RcommandArgs的调用,trailingOnly = TRUE将命令行参数传递到R脚本中。应用程序的名称作为第一个也是唯一的参数传入。该值存储在app变量中,然后将在rmarkdown::render的调用中使用,并在评估.Rmd文件时使用。

    # file: knit-application-report.R
    #
    # Commandline Arguments:
    # 1. appliction a character string for the app
    
    app <- commandArgs(trailingOnly = TRUE)
    
    rmarkdown::render(input = "application-report.Rmd",
                      output_file = paste0(app, ".pdf")) 
    

    命令行看起来像这样(来自我的linux命令行)。

    me@mycomputer:~$ Rscript knit-application-report.R MyApplication
    
    
    processing file: application-report.Rmd
      |................................                                 |  50%
       inline R code fragments
    
      |.................................................................| 100%
    label: unnamed-chunk-1
    
    output file: application-report.knit.md
    
    /usr/bin/pandoc +RTS -K512m -RTS application-report.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output MyApplication.pdf --template /home/pdewitt/R-dev/R-3.4.1/library/rmarkdown/rmd/latex/default-1.17.0.2.tex --highlight-style tango --latex-engine pdflatex --variable graphics=yes --variable 'geometry:margin=1in'
    
    Output created: MyApplication.pdf
    

    请注意,输出是命名报告MyApplication.pdf,如下所示:

    enter image description here

相关问题