This document provides an example of using a single Rmd file to generate output with different content based on the output document type.
The envelope-pushing examples below are complicated, and in many cases require generating strings that are rendered using the structure:
if(is_html_output){
cat("
some R Markdown syntax
")
}
The examples are unlikely–it is hard to imagine a case for which a single Rmd file should generate completely different output. But the examples should serve to demonstrate how different output can be included based on the type of output file.
If this is an HTML document, the following apply:
If this is PDF output, the following apply:
if(is_html_output()){
foo <- ""
cat("Because this is HTML output, a Leaflet map could be included!\n\n")
cat("## A Leaflet Map\n")
}
Because this is HTML output, a Leaflet map could be included!
if(is_html_output()){
# the Space Needle
snxy <- data.frame(name = "Space Needle", x = -122.3493, y = 47.6205)
space_needle <- st_as_sf(snxy, coords = c("x", "y"), crs = 4326)
# a leaflet map
m <- leaflet() %>%
addTiles() %>%
addCircleMarkers(data = space_needle)
m
}
if(is_html_output()){
# make and print the caption
# this creates a string object from the citation, and drops all white space
cap <- fig_captions(name = "Leaflet", caption = "A Leaflet map centered at the Space Needle\n\n")
cat(cap)
cite <- fig_captions(name = "Leaflet", display = "cite")
# This adds the text
cat(sprintf("See the Leaflet map (%s) for details.", cite))
}
Figure 1: A Leaflet map centered at the Space Needle
See the Leaflet map (Figure 1) for details.
# if this is LaTeX output then print the Poisson distribution and use an equation number and cross-reference
if(is_latex_output()){
cat("This is PDF output and therefore a Leaflet map cannot be added.\n\n")
# an equation caption
eqn_captions(name = "poisson", caption = "")
# this creates a string object from the caption, and drops all white space
cite <- eqn_captions(name = "poisson", display = "cite") %>%
str_remove_all(pattern = "\\s")
# This adds the text
cat(sprintf("See the Poisson distribution (%s) for details", cite))
# `cat' to print out an equation
cat("
\\begin{equation}
P(x) = \\frac{ e^{ - \\lambda } \\lambda ^x }{ x! }\
\\end{equation}
")
}
# only print the source code if this is LaTeX output
if(is_latex_output()){
cat("# Source code\n\n")
}
# only print the source code if this is LaTeX output
if(is_latex_output()){
srccode <- readLines(fnamepath) %>%
str_wrap(width = 80, exdent = 4)
cat(srccode, sep = '\n')
}