Posted on 2 minute read

R Markdown is a great way to embed R code in a Markdown document, but it’s also easy to do the inverse: embed Markdown in R code, such as a Shiny app’s UI, with the markdown package.

This makes writing snippets of prose in Shiny app UIs very convenient. Here’s an example:

library(shiny)
library(markdown)

markdown <- function(s) {
  s <- gsub("\\n[ \\t]*", "\n", s)
  HTML(markdownToHTML(fragment.only = TRUE, text = s))
}

ui <- fluidPage(
  markdown("
  # Inline Markdown
  
  This is a demonstration of inline markdown using the `markdown` 
  package.
  
  We can have links to [Google](https://google.com), and even lists 
  like the one below!
  
  1. Foo
  1. Bar
  1. Baz")
)

server <- function(input, output, session) {
}

shinyApp(ui, server)

How it works

  1. base::gsub() is used to remove leading whitespace from each line while preserving empty lines. If you’re on Windows and your R code has \r\n line endings, you’ll need to tweak this part. This transformation allows you to arbitrarily indent your Markdown string, as RStudio (and probably other editors) want to do automatically.
  2. markdown::markdownToHTML() converts the Markdown to a character vector of HTML. fragment.only = TRUE produces an HTML fragment instead of an HTML document with CSS and JavaScript.
  3. shiny::HTML() inserts the HTML into the UI verbatim, without escaping it.