ifelse action depending on document type in rmarkdown

后端 未结 2 589
暖寄归人
暖寄归人 2021-01-02 08:05

When preparing reports using rmarkdown: http://rmarkdown.rstudio.com/ one may want the document to render differently depending upon the document type. For ins

相关标签:
2条回答
  • 2021-01-02 08:28

    Yes, you can access the output format via knitr::opts_knit$get("rmarkdown.pandoc.to"). This will return a string with the target output format. Here's an example:

    ---
    title: "Untitled"
    output: html_document
    ---
    
    ```{r}
    library(knitr)
    opts_knit$get("rmarkdown.pandoc.to")
    ```
    

    This returns "html" for html_document, "docx" for word_document, and "latex" for pdf_document. So to answer your question you can do something like:

    html <- knitr::opts_knit$get("rmarkdown.pandoc.to") == "html"
    
    0 讨论(0)
  • 2021-01-02 08:37

    As pointed out in an answer to a related question, knitr 1.18 introduced the following functions

    knitr::is_html_output()
    knitr::is_latex_output()
    

    As the name suggests, is_html_output() checks if the output is HTML. You would add something like this to foo.Rmd:

    ```{r results='asis'}
    if (knitr::is_html_output()) {
        cat('<iframe width="640" height="390" src="https://www.youtube.com/embed/FnblmZdTbYs?        feature=player_detailpage" frameborder="0" allowfullscreen></iframe>')
    } else {
        cat("https://www.youtube.com/watch?v=ekBJgsfKnlw")
    }
    ```
    
    0 讨论(0)
提交回复
热议问题