Rmarkdown In R

  

RMarkdown is a framework that provides a literate programming format for data science. It can be used to save and execute R code within RStudio and also as a simple formatting syntax for authoring HTML, PDF, ODT, RTF, and MS Word documents as well as seamless transitions between available formats. The name “markdown” is an intentional contrast to other “markup” languages–e.g., hypertext markup language (HTML)–which require syntax that can be quite difficult to decipher for the uninitiated. One aim of the markdown paradigm is a syntax that is as human-readable as possible. “RMarkdown” is an implementation of the “markdown” language designed to accommodate embedded R code.

R Markdown is an authoring format that enables easy creation of dynamic documents, presentations, and reports from R. It combines the core syntax of markdown (an easy-to-write plain text format) with embedded R code chunks that are run so their output can be included in the final document. RMarkdown is a script type used in R to allow for the generation of Markdown from R code. RMarkdown files will typically have the extension. Be aware that Python blocks in R Markdown reports are not run by the built-in DSS Python environment.

What is literate programming ?

Literate programming is the notion for programmers of adding narrative context with code to produce documentation for the program simultaneously. Consequently, it is possible to read through the code with explanations so that any viewer can follow through the presentation. RMarkdown offers a simple tool that allows to create reports or presentation slides in a reproducible manner with collateral advantages such as avoiding repetitive tasks by, for example, changing all figures when data are updated.

What is reproducible research ?

Reproducible research or reproducible analysis is the notion that an experiment’s whole process, including collecting data, performing analysis and producing output, can be reproduced the same way by someone else. Building non-reproducible experiments has been a problem both in research and in the industry, and having such an issue highly decreases the credibility of the authors’ findings and, potentially, the authors themselves. In essence, allowing for reproducible research implies that anyone could run the code (knit the document, etc.) and obtain the same exact results as the original research and RMarkdown is commonly used to address this issue.

Below is a short video showing a basic overview of RMarkdown.

We have created a framework application that you can use to test out different RMarkdown functions. Simply run the following code within the introDS package by using either

Shiny applications not supported in static R Markdown documents

Then a shiny app window will pop out for you to access the application like the following:

As you can see, the toolbar on the left hand side allows you to try different RMarkdown functions. On the right hand side, Raw code shows the original R code that generates the output, Compiled html shows the compiled output based on the Raw code, and BibTex file shows the formatting lists of references.

For example, let’s try to compile some R code within RMarkdown. Click on the Code in the toolbar for some example code:

Then when we click on the Compiled html, we can see the following output:

You can also try multiple functions at the same time. For example, let’s click both Code and Emoji in the toolbar, we can see the following R code used:

The above code generates the following output:

Now you are ready to experiment different RMarkdown functions and test the corresponding outputs! 😉

2.1 Create an R Markdown file in RStudio

Rstudio

Within RStudio, click FileNew FileR Markdown. Give the file a title and the author(your name) and select the default output, HTML. We can change this later so don’t worry about it for the moment.

An RMarkdown is a plain text file that contains three different aspects:

  • YAML metadata
  • Text
  • Code Chunks

2.2 YAML Metadata

YAML stands for YAML Ain’t Markup Language and is used to specify document configurations and properties such as name, date, output format, etc. The (optional) YAML header is surrounded before and after by “—” on a dedicated line.

You can also include additional formatting options such as a table of contents or even a custom CSS style template which can be used to further enhance the presentation. For the purpose of this book, the default options should be sufficient. Below is an example knit output of the above RMarkdown file.

The default output above is an html_document format but this format can be modified using, for example, pdf_document to output a pdf. However, the pdf format requires additional installation and configuration of a TeX distribution such as MikTeX. Once available, the user can also include raw LaTeX and even define LaTeX macros in the RMarkdown document if necessary (we’ll discuss more about LaTeX further on).

2.2.1 Subsections

Markdown in retail

To make your sections numbered as sections and subsections, make sure you specify number_sections: yes as part of the YAML Metadata as shown below.

2.3 Text

Due to its literate nature, text will be an essential part in explaining your analysis. With RMarkdown, we can specify custom text formatting with emphases such as italics, bold, or code style. To understand how to format text, our previous sentence would be typed out as follows in RMarkdown:

2.3.1 Headers

As seen above, headers are preceded by a #. A single # produces the largest heading text while, to produce smaller headings, you simply need to add more #s! Heading level also impacts section and subsection nesting in documents and tables of contents, as well as slide breaks in presentation formats.

2.3.2 Lists

Lists can be extremely convenient to make text more readable or to take course notes during class. RMarkdown allows to create different list structures as shown in the code below:

which delivers the following list structure:

  • You can create bullet points by using symbols such as *, +, or -.
  • simply add an indent or four preceding spaces to indent a list.
    • You can manipulate the number of spaces or indents to your liking.
      • Like this.
    • Here we go back to the first indent.
  1. To make the list ordered, use numbers.
  2. We can use one again to continue our ordered list.
  3. Or we can add the next consecutive number.

2.3.3 Hyperlinks

To add hyperlinks with the full link, (ex: https://google.com/) you can follow the syntax below:

whereas to add hyperlinks with a custom link title, (ex: Google) follow the syntax below:

2.3.4 Blockquotes

Use the > character in front of a line, just like in email to produce blockquotes which styles the text in a way to use if we quote a person, a song or another entity.

“To grow taller, you should shave your head. Remember to bring the towels!”

Justin Lee

2.3.5 Pictures

To add a picture with captions, follow the syntax below:

which will produce:

Otherwise, to add a picture without any captions, follow the syntax below:

which delivers:

2.3.6 LaTeX

LaTeX is a document preparation system that uses plain text as opposed to formatted text that is used for applications such as Microsoft Word. It is widely used in academia as a standard for the publication of scientific documents. It has control over large documents containing sectioning, cross-references, tables and figures.

2.3.6.1 LaTeX in RMarkdown

Unlike a highly formatted word processor, we cannot produce equations by clicking on symbols. As data scientists there is often the need to explain distributions and equations that are behind the methods we present. Within the text section of an RMarkdown document you can include LaTeX format text to output different forms of text, mainly equations and mathematical expressions.

Inline mathematical expressions can be added using the syntax: $math expression$. For example, if we want to write “where (alpha) is in degrees” we would write:

Using a slightly different syntax (i.e. $$math expression$$) we can obtain centered mathematical expressions. For example, the binomial probability distribution in LaTeX is written as

$$f(y N,p) = frac{N!}{y!(N-y)!}cdot p^y cdot (1-p)^{N-y} = {{N}choose{y}} cdot p^y cdot (1-p)^{N-y}$$

Rmarkdown

which is output as:

[f(y N,p) = frac{N!}{y!(N-y)!}cdot p^y cdot (1-p)^{N-y} = {{N}choose{y}} cdot p^y cdot (1-p)^{N-y}]

An introduction to the LaTeX format can be found here if you want to learn more about the basics. An alternative can be to insert custom LaTeX formulas using a graphical interface such as codecogs.

2.3.7 Cross-referencing Sections

You can also use the same syntax @ref(label) to reference sections, where label is the section identifier (ID). By default, Pandoc will generate IDs for all section headers, e.g., # Hello World will have an ID hello-world. To call header hello-world as a header, we type @ref(hello-world) to cross-reference the section. In order to avoid forgetting to update the reference label after you change the section header, you may also manually assign an ID to a section header by appending {#id} to it.

2.3.8 Citations and Bibliography

Citations and bibliographies can automatically be generated with RMarkdown. In order to use this feature we first need to create a “BibTex” database which is a simple plain text file (with the extension “.bib”) where each reference you would like to cite is entered in a specific manner.

To illustrate how this is done, let us take the example of a recent paper where two researchers from Oxford University investigated the connection between the taste of food and various features of cutlery such as weight and color (calling this phenomenon the “taste of cutlery”). The BibTeX “entry” for this paper is given below:

This may look like a complicated format to save a reference but there is an easy way to obtain this format without having to manually fill in the different slots. To do so, go online and search for “Google Scholar” which is a search engine specifically dedicated to academic or other types of publications. In the latter search engine you can insert keywords or the title and/or authors of the publication you are interested in and find it in the list of results. In our example we search for “The taste of cutlery” and the publication we are interested in is the first in the results list.

Below every publication in the list there is a set of options among which the one we are interested in is the “Cite” option that should open a window in which a series of reference options are available. Aside from different reference formats that can be copied and pasted into your document, at the bottom of the window you can find another set of options (with related links) that refer to different bibliography managers.

For “.bib” files we are interested in the “BibTeX” option and by clicking on it we will be taken to another tab in which the format of the reference we want is provided. All that needs to be done at this point is to copy this format (that we saw earlier in this section) and paste in the “.bib” file you created and save the changes.

However, your RMarkdown document does not know about the existence of this bibliography file and therefore we need to insert this information in the YAML metadata at the start of our document. To do so, let us suppose that you named this file “biblio.bib” (saved in the same location as your RMarkdown document). All that needs to be done is to add another line in the YAML metadata with bibliography: biblio.bib and your RMarkdown will now be able to recognize the references within your “.bib” file.

There are also a series of other options that can be specified for the bibliography such as its format or the way references can be used within the text (see links at the end of this section).

Once the “.bib” file has been created and has been linked to your RMarkdown document through the details in the YAML metadata, you can now start using the references you have collected in the “.bib” file. To insert these references within your document at any point of your text you need to use the name that starts the reference field in your “.bib” file and place it immediately after the @ symbol (without spaces). So, for example, say that we wanted to cite the publication on the “taste of cutlery”: in your RMarkdown all you have to do is to type @harrar2013taste at the point where you want this citation in the text and you will obtain: Harrar and Spence (2013). Moreover, it is often useful to put a citation in braces and for example if you want to obtain (see e.g. Harrar and Spence 2013) you can simply write [see e.g. @harrar2013taste].

The user can also change the name that is used to call the desired reference as long as the same name is used to cite it in the RMarkdown document and that this name is not the same as another reference.
The references in the “.bib” file will not appear in the references that are output from the RMarkdown compiling procedure unless they are specifically used within the RMarkdown document.

Additional information on BibTeX and reference in RMarkdown can be found in the links below:

2.3.9 Tables

For simple tables, we can be manually insert values as such follows:

to produce:

FruitPriceAdvantages
Bananas$1.34
  • built-in wrapper
  • bright color
Oranges$2.10
  • cures scurvy
  • tasty

Markdown In Retail

As an alternative we can use the simple graphical user interface online. For more extensive tables, we create dataframe objects and project them using knitr::kable() which we will explain later on this book.

2.3.10 Additional References

There are many more elements to creating a useful report using RMarkdown, and we encourage you to use the RMarkdown Cheatsheet as a reference.

2.4 Code Chunks

Code chunks are those parts of the RMarkdown document where it is possible to embed R code within your output. To insert these chunks within your RMarkdown file you can use the following shortcuts:

  • the keyboard shortcut Ctrl + Alt + I (OS X: Cmd + Option + I)
  • the Add Chunk command in the editor toolbar
  • by typing the chunk delimiters ```{* and ```**.

The following example highlights the code chunks in the example RMarkdown document we saw at the start of this chapter:

2.4.1 Code Chunk Options

A variety of options can be specified to manage the code chunks contained in the document. For example, as can be seen in the third code chunk in the example above, we specify an argument that reads echo = FALSE which is a parameter that was added to the code chunk to prevent printing the R code that generated the plot. This is a useful way to embed figures. More options can be found from the RMarkdown Cheatsheet and Yihui’s notes on knitr options. Here are some explanations of the most commonly used chunk options taken from these references:

  • eval: (TRUE; logical) whether to evaluate the code chunk;
  • echo: (TRUE; logical or numeric) whether to include R source code in the output file;
  • warning: (TRUE; logical) whether to preserve warnings (produced by warning()) in the output like we run R code in a terminal (if FALSE, all warnings will be printed in the console instead of the output document);
  • cache: (FALSE; logical) whether to “cache” a code chunk. This option is particularly important in practice and is discussed in more details in Section 2.4.4.

Plot figure options:

  • fig.path: (‘figure/’; character) prefix to be used for figure filenames (fig.path and chunk labels are concatenated to make filenames);
  • fig.show: (‘asis’; character) how to show/arrange the plots;
  • fig.width, fig.height: (both are 7; numeric) width and height of the plot, to be used in the graphics device (in inches) and have to be numeric;
  • fig.align: (‘default’; character) alignment of figures in the output document (possible values are left, right and center;
  • fig.cap: (NULL; character) figure caption to be used in a figure environment.

2.4.3 In-line R

The variables we store in an RMarkdown document will stay within the environment they were created in. This means that we can call and manipulate them anywhere within the document. For example, supposing we have a variable called x to which we assign a specific value, then in RMarkdown we can reference this variable by using r x: this will affix the value of the variable directly in a sentence. Here is a practical example:

where we have stored the value 2 in a variable called a. We can use the value of a as follows:

This translates in R Markdown to “The value of (a) is 2.”

2.4.4 Cache

Depending on the complexity of calculations in your embedded R code, it may be convenient to avoid re-running the computations (which could be lengthy) each time you knit the document together. For this purpose, it possible to specify an additional argument for your embedded R code which is the cache argument. By default this argument is assigned the value FALSE and therefore the R code is run every time your document is compiled. However, if you specify this argument as cache = TRUE, then the code is only run the first time the document is compiled while the following times it simply stores and presents the results of the computations when the document was first compiled.

Below is a short video introducing caching in R Markdown.

The RMarkdown file used for this particular example can be found here: caching.Rmd.

Let us consider an example where we want to embed an R code with a very simple operation such as assigning the value of 2 to an object that we call a (that we saw earlier). This is clearly not the best example since this operation runs extremely quickly and there is no visible loss in document compilation time. However, we will use it just to highlight how the cache argument works. Therefore, if we want to avoid running this operation each time the document is compiled, then we just embed our R code as follows:

which would be written in RMarkdown as:

You will notice that we called this chunk of embedded R code computeA and the reason for this will become apparent further on. Once we have done this we can compile the document that will run this operation and store its result. Now, if we compile the document again (independently from whether we made changes to the rest of the document or not) this operation will not be run and the result of the previous (first) compiling will be presented. However, if changes are made to the R code which has been “cached”, then the code will be run again and this time its new result will be stored for all the following compilings until it is changed again.

This argument can therefore be very useful when computationally intensive R code is embedded within your document. Nevertheless it can suffer from a drawback which consists in dependencies of your “cached” R code with other chunks within the document. In this case, the other chunks of R code can be modified thereby outputting different results but these will not be considered by your “cached” R code. As an example, suppose we have another chunk of R code that we can “cache” and that takes the value of a from the previous chunk:

which would be written in RMarkdown as:

In this case, the output of this chunk will be ## 4 since a <- 2 (from the previous chunk). What happens however if we modify the value of a in the previous chunk? In this case, the previous chunk will be recomputed but the value of d (in the following chunk) will not be updated since it has stored the value of 4 and it is not recomputed since this chunk has not been modified. To avoid this, a solution is to specify the chunks of code that the “cached” code depends on. This is why we initially gave a name to the first chunk of code (“computeA”) so as to refer to it in following chunks of “cached” code that depend on it. To refer to this code you need to use the option dependson as follows:

which we would write as:

In this manner, if the value of a changes in the first chunk, the value of d will also change but will be stored until either the computeA chunk or the latter chunk is modified.

2.5 Render Output

After you are done, run RMarkdown::render() or click the Knit button at the top of the RStudio scripts pane to save the output in your working directory.

The use of RMarkdown makes it possible to generate any file format such as HTML, pdf and Word processor formats using pandoc. Pandoc is a free software that understands and converts useful markdown syntax, such as the code mentioned above, into a readable and clean format.

2.6 Addition Information

Click on the links below for more information on RMarkdown:

Output Metadata¶

Carbon copy cloner review. 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.

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

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¶

Rmarkdown In Rstudio

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¶

Rmarkdown

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.