30-04-2021



  1. Rmarkdown Table
  2. Rmarkdown Slides
  3. Rmarkdown New Page
  4. Rmarkdown Tutorial

Output Metadata¶

Rmarkdown

R Markdown supports all of the base pandoc markdown features as well as some optional features for compatibility with GitHub Flavored Markdown (which previous versions of R Markdown were based on). See rmarkdownformat for details. RMarkdown input content. You can now assign text blocks in your R markdown file specific styles. Here I created 3 styles called mystyle1/mystyle2/mystyle3 in the Word doc, and assign them to specific parts of the text. This example markdown text shows how to use the styles. # A regular section This text is not getting a special format. Overview The rmarkdown package helps you create dynamic analysis documents that combine code, rendered output (such as figures), and prose. You bring your data, code, and ideas, and R Markdown renders your content into a polished document that can be used to: Do data science interactively within the RStudio IDE.

We normally think of R Markdown documents as producing a single outputartifact, such as an HTML or PDF file. The rmarkdown package allows reportauthors to emit additional output metadata from their report. RStudio Connecttakes advantage of this metadata, allowing output files, custom emailsubjects, and additional email attachments.

There are two ways to set output metadata: in the YAML header and in R codechunks.

The YAML header is a good place to configure default values for metadata thatyou always want to emit. All output metadata lives under thermd_output_metadata section in the YAML:

You can also use R code to set output metadata. This is useful if you wantmetadata to vary based on conditions or variables within your code.

Your R code can also read the current state of your output metadata. This canhelp you gradually alter this information as the report runs.

Note

The rmd_output_metadata names starting with rsc_ are reserved for use with RStudio Connect.

Output Files¶

Introduction to Output Files¶

Output files are files that live alongside your rendered report. They couldbe plots, data files, or other artifacts generated from the R code in yourreport. Output files will be available via HTTP, and they will be versioned inthe same way as your report. Output files are also subject to the same accesscontrols as your report.

File

Connect will not process any output files that exist outside the workingdirectory of the report that is rendering. That means that you cannot useabsolute paths (e.g., /root/file.csv) or relative paths (e.g., ../file.csv).

How to Work with Output Files¶

There are two ways to specify which files should be treated as output files.The first is to list the file names in the R Markdown YAML header'srmd_output_metadata section under rsc_output_files, like so:

rsc_output_files takes a list of names of files that should be availableafter the report has rendered. If you list a file that does not exist afterrendering your report, Connect will log a message but continue trying toprocessing the other files listed. If the output files are not generatedduring the rendering of your report, then you need to list them as resourcefiles when you upload your report to Connect. See ResourceFiles for more information.

It is also possible to specify the list of output files from R code.For example:

Output files can be contained within sub-directories; the relative directorystructure is maintained.

To include a directory:

You can also make a link to share an output file from your report using thestandard Markdown links as supported in R Markdown. For example, if you want toshare a file named data.csv, you make a link to it in your report like this:

Because output files are versioned along with the rendering of their report,they also benefit from historical views. In the example above, if you viewa historical rendering of the report, when you click on the data.csv link,you will get a download of the file from the same point in time as the report.

Accessing output files over HTTP¶

Content deployed to http://connect.mycompany.com/content/42/ will have itsoutput files available under that URL path. An output file nameddaily-summary.csv will be available at the URLhttp://connect.mycompany.com/content/42/daily-summary.csv.

The URL for your content is the same as its 'Open Solo' location and isavailable in the RStudio Connect dashboard.

Resource Files¶

If you want RStudio Connect to host a file that you have in your report's sourcedirectory on your computer, and that file is not generated by the report whenyou render it, then you will need to mark that file as a resource file. Like anoutput file, a resource file can be a plot, a data file, or any other artifactthat exists as a file. You can use the RStudio IDE to select resource files, oryou can list them in the R Markdown header:

Unlike rsc_output_files, the resource_files key is not nested underrmd_output_metadata. If you do not list your resource files underresource_files, then you will need to add them manually using the 'AddMore...' button when deploying from the IDE. See the Publishingsection for more information on publishing additionalresource files.

Email Customization¶

RStudio Connect makes it easy to schedule reports that distribute emails. Theseemails, by default, contain a link to the report. However, it is possible tofully customize the email, and distribute results directly tousers without requiring them to leave their inbox.

There are two approaches for customizing email in Connect. One approach is todirectly set R Markdown OutputMetadata. This option is the mostflexible, but also the hardest to use. The second approach is to use theblastula package. Using the blastulapackage is the easiest way to get started and is recommended for most use cases.

Getting Started with Custom Emails¶

To get started with custom emails, we recommend using theblastula package. The easiest way tostart is by installing the package and using the included example:

This command will create a new folder in your workspace with a number of examplefiles. In general, the approach when using blastula is to create a new RMarkdown document responsible for crafting the email. This R Markdown documentis then attached to your original document by including the following code inthe main R Markdown file:

Info

This code is an example from the final code chunk found inconnect-example-main.Rmd Rendering the main report will create a previewof the custom email. When you publish to RStudio Connect, simply include thechild R Markdown document responsible for the email as a supporting file.

Using R Markdown Metadata¶

Instead of using the blastula package, it is possible to construct custom emails using R Markdown Output Metadata. A quick summary of the output metadata options are:

OptionDescription
rsc_email_subjectA character string giving the email subject line
rsc_email_body_textA character string to be used as the plain-text body of the email
rsc_email_body_htmlA character string that results in HTML to be rendered in the body of the email
rsc_email_attachmentsA list of relative file paths for files to be attached to the email
rsc_email_imagesA named list, where the key matches the CID name of the image in the email body, and the object is a base64 encoded image.
rsc_email_supress_scheduledA boolean, whether to send the scheduled email (FALSE) or suppress the email (TRUE)
rsc_email_suppress_report_attachmentA boolean, whether to include the rendered report as an attachment to the email

To set an option, use code like:

The following sections describe the individual options in more detail.

Email Subject¶

You can customize the subject line used when an email of a report isgenerated. RStudio Connect uses the output metadata entry namedrsc_email_subject as email subject. A report without an rsc_email_subjectentry uses its published document name.

Use the YAML header to specify a simple, static text override of the emailsubject:

Set the email subject in an R code chunk if you need to dynamically build thesubject:

The RSC_EMAIL_SUBJECT environment variable contains the name of yourpublished report, which also acts as the default email subject. Thisenvironment variable is helpful if you want to add, but not fully replace thesubject.

Note

Rmarkdown

The value of RSC_EMAIL_SUBJECT is computed when your report is rendered.Changes to the report name will be incorporated into subsequent renderings.

You can also read the current subject from the output metadata toincrementally compose a final subject.

Email Body¶

A report can customize the message body used when an email for that report issent. RStudio Connect uses the output metadata entry namedrsc_email_body_text for plain-text bodies and rsc_email_body_html for HTMLbodies. A report with neither entry uses an automatically generated,plain-text body with a link to the report's URL.

Text Message Bodies¶

Use the YAML header to specify a simple, static text override of the emailbody:

The message in the email client would look similar to the following:

Set the body text in an R code chunk if you need to dynamically build themessage:

You can also read the current body from the output metadata toincrementally compose a final body.

The glue package can help with more complicatedformatting.

HTML Message Bodies¶

The rsc_email_body_html attribute specifies an HTML-formatted message body.RStudio Connect sets the content-type of the message so that most emailclients will display the HTML message correctly.

Note

Use rsc_email_body_text together with rsc_email_body_html to supply textthat older email clients can display while allowing newer clients to displayyour rich content.

The YAML header can specify a simple, static HTML override of the email body:

You can build the HTML message dynamically:

Composing and styling HTML email messages is different than buildingtraditional web pages. Email messages cannot embed scripts nor referenceexternal stylesheets. Email clients may implement additional restrictions.

Note

Not all email clients display HTML messages exactly the same. Send yourselfa test message to check basic formatting, then confirm with your audiencethat the message appears correctly in their email client.

Embedding Images in HTML Email¶

Info

For emails including images or tables, we highly recommend using the blastula package.

It is possible to embed images, such as plots, within HTML email, using thersc_email_images attribute in rmd_output_metadata. The embedded image musthave a Content ID that is used in the body of the HTML and when providing theimage to rsc_email_images, and the image itself must be base64-encoded. Hereis an example:

Including URLs and Other Details¶

You may want to customize your email with a link to the location of the reportin RStudio Connect or to give your email recipients a way to manage their emailsubscription. RStudio Connect provides the R Markdown render with environmentvariables that can be referenced from your code.

Variable NameExample Value
RSC_REPORT_NAME'Quarterly Sales Summary'
RSC_REPORT_RENDERING_URL'http://rsc.company.com/content/42/_rev1/'
RSC_REPORT_SUBSCRIPTION_URL'http://rsc.company.com/connect/#/apps/42/subscriptions'
RSC_REPORT_URL'http://rsc.company.com/content/42/'

Note

The value of RSC_REPORT_NAME is computed when your report is rendered.Changes to the report name will be incorporated into subsequent renderings.

The final values of the URL environment variables are not known prior to rendering. RStudio Connect renders your document using placeholder values for these environment variables. The placeholder values are replaced when constructing the final email message. These URLs are not appropriate for use in the body of your report.

Use the Sys.getenv() function to get the values for these environmentvariables in your report. When rendering your report outside of RStudio Connect,these environment variables will not have values. Use the second argument toSys.getenv() to provide a temporary value.

You can use these variables anywhere within your email body or footer.

Email Attachments¶

An attachment is an output file that will be attached to an emailed report. Youcan specify email attachments as an argument to theblastulaattach_connect_emailfunction, or using the rsc_email_attachments R Markdown Output Metadata.

For example, using blastula:

For example, using output metadata:

For nested files, include the relative path:

An email attachment will be accessible via HTTP just like an output file, andyou can make a link to it in your report in the same way.

Some mail systems have limitations on attachments in email messages.Attachments from your report need to follow the restrictions enforced by yourorganization. Connect is not aware of those limitations. Please work withyour systems administrators / IT organization if you have trouble deliveringfile attachments.

Conditionally Sending Email¶

By default, reports can be configured to run on a regular schedule. However, youmay only want to send an email to stakeholders under certain conditions. Forexample, you could have a report that runs every day to check supply levels, butonly sends an email notification if supplies dip below a critical threshold.

This behavior can be configured with the blastula package or using R MarkdownOutput Metadata.

Using blastula you can craft an if statement around the call to attach_connect_email:

Using R Markdown Output Metadata follows a similar pattern with an if statement:

Suppress Attaching Report To Email¶

By default, Connect adds the generated document as an attachment to emailmessages for that report. You can prevent this attachment from your R Markdownreport by giving the rsc_email_suppress_report_attachment metadata property alogical (Boolean) value or using the attach_output = FALSE argument inblastula::attach_connect_email.

Note

Attachments configured by the rsc_email_attachments metadata property(seecEmail Attachments) are still attachedand not affected by the rsc_email_suppress_report_attachment setting.

Tracking Visits¶

Connect records visits to R Markdown documents and lets you see:

  • Which documents were viewed
  • When the documents were viewed
  • Who viewed the documents

Details about visits are also recorded for parameterized R Markdown documentsand other types of rendered and static content.

An overview of recent activity is available in the RStudio Connect dashboard.See the Content Settings Panel section to learn more.

Details about each visit are available through the InstrumentationAPIs. Use these records to perform your ownanalysis. Code examples showing how to obtain this data can be found in theUser Activity section of the RStudio Connect:Server API Cookbook.

Interactive documents are a new way to build Shiny apps. An interactive document is an R Markdown file that contains Shiny widgets and outputs. You write the report in markdown, and then launch it as an app with the click of a button.

This article will show you how to write an R Markdown report.

The companion article, Introduction to interactive documents, will show you how to turn an R Markdown report into an interactive document with Shiny components.

R Markdown

R Markdown is a file format for making dynamic documents with R. An R Markdown document is written in markdown (an easy-to-write plain text format) and contains chunks of embedded R code, like the document below.

R Markdown files are designed to be used with the rmarkdown package. rmarkdown comes installed with the RStudio IDE, but you can acquire your own copy of rmarkdown from github with the command

R Markdown files are the source code for rich, reproducible documents. You can transform an R Markdown file in two ways.

  1. knit - You can knit the file. The rmarkdown package will call the knitr package. knitr will run each chunk of R code in the document and append the results of the code to the document next to the code chunk. This workflow saves time and facilitates reproducible reports.

    Consider how authors typically include graphs (or tables, or numbers) in a report. The author makes the graph, saves it as a file, and then copy and pastes it into the final report. This process relies on manual labor. If the data changes, the author must repeat the entire process to update the graph.

    In the R Markdown paradigm, each report contains the code it needs to make its own graphs, tables, numbers, etc. The author can automatically update the report by re-knitting.

  2. convert - You can convert the file. The rmarkdown package will use the pandoc program to transform the file into a new format. For example, you can convert your .Rmd file into an HTML, PDF, or Microsoft Word file. You can even turn the file into an HTML5 or PDF slideshow. rmarkdown will preserve the text, code results, and formatting contained in your original .Rmd file.

    Conversion lets you do your original work in markdown, which is very easy to use. You can include R code to knit, and you can share your document in a variety of formats.

In practice, authors almost always knit and convert their documents at the same time. In this article, I will use the term render to refer to the two step process of knitting and converting an R Markdown file.

You can manually render an R Markdown file with rmarkdown::render(). This is what the above document looks like when rendered as a HTML file.

In practice, you do not need to call rmarkdown::render(). You can use a button in the RStudio IDE to render your reprt. R Markdown is heavily integrated into the RStudio IDE.

Getting started

To create an R Markdown report, open a plain text file and save it with the extension .Rmd. You can open a plain text file in your scripts editor by clicking File > New File > Text File in the RStudio toolbar.

Be sure to save the file with the extension .Rmd. The RStudio IDE enables several helpful buttons when you save the file with the .Rmd extension. You can save your file by clicking File > Save in the RStudio toolbar.

R Markdown reports rely on three frameworks

  1. markdown for formatted text
  2. knitr for embedded R code
  3. YAML for render parameters

The sections below describe each framework.

Markdown for formatted text

.Rmd files are meant to contain text written in markdown. Markdown is a set of conventions for formatting plain text. You can use markdown to indicate

  • bold and italic text
  • lists
  • headers (e.g., section titles)
  • hyperlinks
  • and much more

The conventions of markdown are very unobtrusive, which make Markdown files easy to read. The file below uses several of the most useful markdown conventions.

Markdown is an easy to use format for writing reports. It resembles what you naturally write every time you compose an email. In fact, you may have already used markdown without realizing it. These websites all rely on markdown formatting


The file demonstrates how to use markdown to indicate:

  1. headers - Place one or more hashtags at the start of a line that will be a header (or sub-header). For example, # Say Hello to markdown. A single hashtag creates a first level header. Two hashtags, ##, creates a second level header, and so on.

  2. italicized and bold text - Surround italicized text with asterisks, like this *without realizing it*. Surround bold text with two asterisks, like this **easy to use**.

  3. lists - Group lines into bullet points that begin with asterisks. Leave a blank line before the first bullet, like this:

    This is a list

    • item 1
    • item 2
    • item 3
  4. hyperlinks - Surround links with brackets, and then provide the link target in parentheses, like this [Github](www.github.com).

    You can learn about more of markdown’s conventions in the Markdown Quick Reference guide, which comes with the RStudio IDE.

    To access the guide, open a .md or .Rmd file in RStudio. Then click the question mark that appears at the top of the scripts pane. Next, select “Markdown Quick Reference”. RStudio will open the Markdown Quick Reference guide in the Help pane.

Rendering

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want.

When you click the button, rmarkdown will duplicate your text in the new file format. rmarkdown will use the formatting instructions that you provided with markdown syntax.

Rmarkdown Table

Once the file is rendered, RStudio will show you a preview of the new output and save the output file in your working directory.

Here is how the markdown script above would look in each output format.

Note: RStudio does not build PDF and Word documents from scratch. You will need to have a distribution of Latex installed on your computer to make PDFs and Microsoft Word (or a similar program) installed to make Word files.

knitr for embedded R code

Rmarkdown Slides

The knitr package extends the basic markdown syntax to include chunks of executable R code.

When you render the report, knitr will run the code and add the results to the output file. You can have the output display just the code, just the results, or both.

To embed a chunk of R code into your report, surround the code with two lines that each contain three backticks. After the first set of backticks, include {r}, which alerts knitr that you have included a chunk of R code. The result will look like this

When you render your document, knitr will run the code and append the results to the code chunk. knitr will provide formatting and syntax highlighting to both the code and its results (where appropriate).

As a result, the markdown snippet above will look like this when rendered (to HTML).

To omit the results from your final report (and not run the code) add the argument eval = FALSE inside the brackets and after r. This will place a copy of your code into the report.

To omit the code from the final report (while including the results) add the argument echo = FALSE. This will place a copy of the results into your report.

echo = FALSE is very handy for adding plots to a report, since you usually do not want to see the code that generates the plot.

echo and eval are not the only arguments that you can use to customize code chunks. You can learn more about formatting the output of code chunks at the rmarkdown and knitr websites.

Inline code

To embed R code in a line of text, surround the code with a pair of backticks and the letter r, like this.

knitr will replace the inline code with its result in your final document (inline code is always replaced by its result). The result will appear as if it were part of the original text. For example, the snippet above will appear like this:

YAML for render parameters

You can use a YAML header to control how rmarkdown renders your .Rmd file. A YAML header is a section of key: value pairs surrounded by --- marks, like below

The output: value determines what type of output to convert the file into when you call rmarkdown::render(). Note: you do not need to specify output: if you render your file with the RStudio IDE knit button.

Rmarkdown New Page

output: recognizes the following values:

  • html_document, which will create HTML output (default)
  • pdf_document, which will create PDF output
  • word_document, which will create Word output

If you use the RStudio IDE knit button to render your file, the selection you make in the gui will override the output: setting.

Slideshows

You can also use the output: value to render your document as a slideshow.

  • output: ioslides_presentation will create an ioslides (HTML5) slideshow
  • output: beamer_presentation will create a beamer (PDF) slideshow

Note: The knit button in the RStudio IDE will update to show slideshow options when you include one of the above output values and save your .Rmd file.

rmarkdown will convert your document into a slideshow by starting a new slide at each header or horizontal rule (e.g., ***).

Visit rmakdown.rstudio.com to learn about more YAML options that control the render process.

Recap

R Markdown documents provide quick, reproducible reporting from R. You write your document in markdown and embed executable R code chunks with the knitr syntax.

You can update your document at any time by re-knitting the code chunks.

You can then convert your document into several common formats.

R Markdown documents implement Donald’s Knuth’s idea of literate programming and take the manual labor out of writing and maintaining reports. Moreover, they are quick to learn. You already know ecnough about markdown, knitr, and YAML to begin writing your own R Markdown reports.

In the next article, Introduction to interactive documents, you will learn how to add interactive Shiny components to an R Markdown report. This creates a quick workflow for writing light-weight Shiny apps.

Rmarkdown Tutorial

To learn more about R Markdown and interactive documents, please visit rmarkdown.rstudio.com.