1 Overall Description

The following code/output/plots were served as examples of presenting analysis using R Markdown.


2 Pseudo Data

A pseudo dataset was created to illustrate functions/codes. The data was created using random sampling completely, and the topic of the data is mimicking a class of college students.


3 Essential Packages

library(rmarkdown)
library(knitr)
## Warning: package 'knitr' was built under R version 4.0.5


4 Book and Cheatsheet

First thing first, check out this cheatsheet.

Next, check out the online version of the original book.


5 YAML Setting

5.1 YAML title/author and other first-level arguments

title: "xxxxx"

subtitle: "xxxxx"

author: "xxxxx"

date: "xxxxx" (automatic date "2021-10-01")

output: "xxxx_document" (select output format [word_document, html_document, latex_document, md_document, pdf_document, github_document and some others])

output: "html_notebook" (notebook is another output style which has some difference comparing to xxxx_document)

output: "xxxx_presentation" (presentation files can also be rendered, such as: powerpoint_presentation, ioslides_presentation, beamer_prsentation)

output: rmarkdown::html_vignette (lightweight alternative to html_document suitable for inclusion in package to be released to CRAN)

html_document is used to present all of the following features. Some features may not be applicable for certain document types, for example, the paged table is not going to work in pdf document. However, html is the most flexible document type.


5.2 YAML document options

Under output:, put indented xxxx_document:, followed by certain document specifications, including:

xxxx_document:

  toc: ture (include table of content, indented within xxxx_document:)

  toc_depth: 3 (include top 3-levels of headers in the toc)

  toc_float: ture (make the table of content float to the left of the document)

  toc_collapsed: true (only show the top levels (H1-H2) in the table of contents)

  code_folding: hide (show R code by default, but allow readers to hide the code if they wish)

  df_print: default (a generic method of printing data frame), paged (cerate pageable table), kable (use knitr::kable function), tibble (print tibble version)

  number_sections: true (allow the table of content automatically assign numbers to each section)

  theme: whatever_you_choose (specify theme, e.g. default, cerulean, journal flatly, readable, spacelab, unitetd, cosmo, lumen, paper, sandstone, simplex, yeti, null)

  highlight: tango (specify syntax highlighting style, e.g. default, tango, pygments, kate, monochrome, espresso, zenburn, haddock, textmate, null)

  css: xxx.css (add customized CSS to the html document; this will require the theme & highlight to be set as null)

These specifications need to be further indented.


5.3 YAML parameterized report

5.3.1 create parameters in the report

If you want to include parameter for the whole report, you can specify it in the YAML, like:

output: xxx_document
params:
  date: !r lubridate::today()
  year: !r lubridate::year(today())
  location: "Tampa, FL"
  author: "Eli"
  data: 
  printcode: TRUE

Then a list called params will be created containing all the specified object. However, note not to include rm(list=ls()) inside the markdown file. Otherwise, the params object will be removed.

Subsequently, without specifying them in any R code chunk, you can call them from the params list. Note, they can be used inside an R code chunk, and also in the specifications of the code chunk.

paste0("Today is ", params$date, ". This document is created by ", params$author, ", when he lives in ", params$location, ". He kept working on it during the summer of ", params$year, ".")
## [1] "Today is 2021-10-01. This document is created by Eli, when he lives in Tampa, FL. He kept working on it during the summer of 2021."

5.3.2 update the parameters using the render() function

Instead of knitting the document directly from RStudio, one can choose to use the render function. While using the render function, one can change the existing parameters to create a different report. For example:

render("A personal summary of R Markdown coding.rmd", 
       output_format = "html_document",
       params = list(year = 2018,
                    location = "Wuhan, Hubei",
                    author = "Yayi",
                    printcode = F))

It is obvious now that you can functionize this process and loop through the render function and create a list of documents using just the render function.

5.3.3 interactive user interface for setting parameters

Believe it or not, you can also set the parameters in a cool and interactive interface by:

render("A personal summary of R Markdown coding.rmd", 
       output_format = "html_document",
       params = "ask")


5.4 YAML add header/pre-text/post-text styling

under xxxx_document:, put indented includes:, followed by certain styling specifications which should be also indented, including:

xxxx_document:
  includes:
    in_header: header.html (header.tex if using pdf_document)
    before_body: before.html (similar as above, before.tex if using pdf_document)
    after_body: after.html (...)

Note: all these html files should have the same YAML settings as the main document.


5.5 YAML editor options:

This is specified at the top-level, not under output:.

editor_options: (can also include specified editor's option) chunk_output_type: console (specify to show output in console, instead of the default which is below the code-chunk, indented within editor_options:)


5.6 YAML shared YAML options:

One can specify a set of default options to be used by multiple documents under the same directory. To achieve that, create a a file named _output.yml under the directory. Within the file, put in the specific YAML settings like:

html_documents:
  theme: united

Note that no need to put --- before or after the setting.


5.7 YAML reference a specific docx style

One can use the exact same style of docx document in the R Markdown file they are writing. This is especially useful when you want to output a set of word_documents and keep them the same format.

word_documents:
  reference_docx: "referenced.docx"


5.8 YAML other html formats

The prettydoc package contains a few other themes (and code highlighting style) that are not included in the original rmarkdown package. One can use them by changing the YAML to:

output:
  prettydoc::html_prettuy:
    theme: cayman, tactile, architect, leonids, hpstr
    highlight: github, vignette

The rmdformats package also provides several html output formats of unique and attractive style:

output: rmdformats::material, readthedown, html_clean, html_docco


5.9 YAML include a logo alongside the title

A logo can be added besides to title by including an R code chunk like the following:

|```{r, echo=F}
|htmltools::img(src = "logo.png",
|               alt = 'logo',
|               style = 'position:absolute; top:80px, right:30px; padding:10px; width:200px; height:65px;')
|```


6 Shared Markdown Syntax (html as an example)

6.1 Syntax inline texts

italic *italic texts*

bold **bold texts**

regular textssubscript ~subscript texts~

regular textssuperscript ^superscript texts^

underlined text <span style="text-decoration:underline">underlined text</span> Note: underlining is usually not recommended in markdown writing.

hyperlink [link_name](address)

in-doc link [link_name][in-file section name]

image ![image_name](address){width=50%}

1 ^[footnote texts]


add a empty line <br>


6.2 Syntax header and bullets

6.2.1 header (third-level)

### header (third-level)

6.2.1.1 fourth-level header

#### fourth-level header

header without numbering

### header without number {-}

6.2.2 bullets

  • first-level bullet * first-level bullet, can use */-/+

    • second-level bullet indented * second-level bullet
  1. first-level numbered bullet 1. first-level numbered bullet

    • un-numbered second-level bullet indented - un-numbered second-level bullet


6.3 Syntax quotes

6.3.1 chunk of quotes

“Mastering others is strength. Mastering yourself is true power.”

— Laozi

Quotes can be included following > sign.

6.3.2 chunk of unevaluated texts

Un-evaluated texts can be entered between two sets of three back ticks ```. 
    Indentation can be achieved with 4 white paces before the texts. 

Alternatively, you can include un-evaluated texts that are short by entering texts between two single back ticks.


6.4 Syntax add R code chunk

# Hold Ctrl + Alt + i, to add a R code chunk.

Alternatively, can also put within two back ticks, the letter followed by whatever R code you want to evaluate. For example, see the number of students in the pseudo data set had found a job is 26, which is output by entering “r sum(PseudoData$Employed %in%”Yes“)” within a pair of single back tick.

6.4.1 specification in R code chunk

When adding a R code chunk, you are able to specify options for the output of the code chunk by adding specifications.

{r, ...} 

Here are some options can be specified for individual code chunk.

**General**
eval = T (evaluate the code in the chunk)
echo = T (print out the code in the output document)
results = "hide" (text output will be hide, "asis": text output is written)
collapse = T (make the output more compact)
warning = T (show warnings in the output document, F: show message in the console)
message = T (show messages in the output document, F: show message in the console)
error = T (show errors in the output document, F: halt on error in code chunk)
include = T (include code chunk in the output, F: do not include code chunk in the output, but still evaluate)

**Figure**
fig.width = 4 (set figure width to 4)
fig.height = 5 (set figure height to 5)
fig.dim = c(4, 5) (set figure width and height at the same time)
fig.align = "left", "center", "right" (align figure different horizontal location)
dev = "pdf", "png", "svg", "jpeg" (specify graphical device to record R plots)
fig.cap = "caption" (assign a caption to the figure)
fig.hold = "hold, out.width = "50%" (these two specifications work together to arrange two figure in the same row, each taking 50% of the space)

**Paged Table** only works if the df_print: paged
max.print = 5 (print only the first 5 rows of data frame)
rows.print = 5 (display 5 rows of data on this page)
cols.print = 5 (display 5 columns of data on this page)
cols.min.print = 5 (set the minimum number of 5 cols to display)
pages.print = 5 (only display 5 pages in the page navigator)
paged.print = T (turn on paged tables)
rownames.print = T (show row names in printed table)

If certain options is used throughout the document, a universal setup can be specified upfront.

{r, setup, eval = T, echo = F, fig.dim = c(4, 5)}

In addition, the specifications can be replaced with soft coding, for example:

do_or_not <- Sys.Date() > "2021-05-22"
{r, eval = do_or_not, echo = do_or_not, fig.dim = c(4, 5)}


6.5 Syntax math expression

I know too little about math expression and I barely use any in my daily work. Thus, this is pending more knowledge on my end before proceeding.


6.6 Syntax graphs and tables - showing in split tabs

A section can be split into multiple tabs by adding {.tabset} after the section header

6.6.1 graphs

A graph can be included by using the “image” method described previously or by adding R command within the code chunk.

knitr::include_graphics("C:/Users/ely94/Downloads/lake-3670864_1920.jpg")
This is a nice picture.

This is a nice picture.

## The corresponding r chunk specifications are: ```{r, out.width="50%", fig.align="center", fig.cap="This is a nice picture."}

6.6.2 tables

One of the easiest way of including a formatted table is to use kable.

knitr::kable(head(iris), caption = "first 5 rows of iris data")
first 5 rows of iris data
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

Or set df_print: paged in YAML, and customize the chunk-specification.

iris


6.7 scrollable plots

Sometimes a plot can be too long/wide to present nicely in the markdown document. When that happens, consider making the plot image scrollable. Scrollable plot can be achieved in two steps, 1) adding a css style, 2) wrap the plot within the style.

<style>
.hvscroll-plot {
width: 800px;
height: 500px;
overflow-y: scroll;
}
</style>



<div class="hvscroll-plot">
plot_code
</div>


6.8 Syntax lots of other items

A lot of other items can be added to a R Markdown file, especially if outputting an html document. The “htmlwidgets” package allows for interactive graphs and tables, the “DT” package is also an excellent way of adding data table, the “leaflet” package has great use of presenting interactive map, while the “dygraphs” works well when you want to achieve interactive visualization. You can also create a “shiny” document which combines the R Markdown document feature with the use of a shiny application.


6.9 Syntax changing text font size

Text font size can be changed as a part of css. However, if text size is the only thing you want to change, you can include the short paragraph in below at the beginning of the document (note: not in a R code chunk).

<style type="text/css">
  body{
  font-size: 12pt;
}
</style>


7 Other Outputs

7.1 Outputs Presentation

See this RMD file for details of R Markdown application on presentation.

See this output file for the example of ioslide presentation.

library("rmarkdown")
library("knitr")
render("R Markdown Presentation.rmd", output_format = "ioslides_presentation", quiet = T)


7.2 Outputs Dashboard

See this RMD file for details of R Markdown application on dashboard.

library("rmarkdown")
library("knitr")
render("R Flex Dashboard.Rmd", quiet = T)

See this output file for example of Flex dashboard.

Shiny dashboard is also a great use of presenting data-based story in a dashboard format. We will look into that in more details when we get to read the book “Mastering Shiny” by Hadley Wickham.

7.3 Outputs Other formats

R Markdown is also able to output other formats of files, such as:

Tufte Handouts;

xaringan presentation;

Website;

HTML document for R package;

books;

journal/manuscript;

interactive tutorial;

However, the above mentioned are not particularly what I use regularly, thus we’ll save them for the future. If I were ever need to use any of the above formats, I’ll be adding them to the main document.

In case you came from inline texts.


  1. An example of footnote↩︎