2

I'm using code externalization in knitr. I have an myRcode.R file that includes codes and I have two kinds of reports I want to produce. One latex file (myLatexFile.RNW) and one html file (myHtmlFile.RMD). Both are calling chunks from the myRcode.R file. I want to get different outputs depending on the extension that calls the chunk.

Right now, my solution is this something like this:

library(stringr)
if (str_sub(current_input(),-3,-1) == "Rmd") {
  cat("HTML file...")
} else if (str_sub(current_input(),-3,-1) == "Rnw") 
  cat("LATEX file...")

But there should be a native function that gets the file type within the knitr. I couldn't find it. Is there such function in knitr?

HBat
  • 4,873
  • 4
  • 39
  • 56
  • 1
    See this as I think it will be of use: https://trinkerrstuff.wordpress.com/2014/11/18/rmarkdown-alter-action-depending-on-document/ – Tyler Rinker Mar 28 '15 at 11:37
  • In theory `knitr::opts_knit$get("rmarkdown.pandoc.to")` is what I want. But it returns `NULL` when I knit a latex document. For html files it works though. – HBat Mar 28 '15 at 15:28
  • Possible duplicate of [In \`knitr\` how can I test for if the output will be PDF or word?](http://stackoverflow.com/questions/35144130/in-knitr-how-can-i-test-for-if-the-output-will-be-pdf-or-word) – CL. Aug 29 '16 at 07:21

1 Answers1

2

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

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

which check at compile-time if the output is HTML or LaTeX, and return TRUE/FALSE. Something like the following would work:

if (knitr::is_html_output()) {
  cat("HTML file...")
} else if (knitr::is_latex_output()) { 
  cat("LATEX file...")
}
Frank
  • 2,386
  • 17
  • 26