Introduction to R Markdown

Mark Lai
January 13, 2022

RStudio Intro

print("This is Thursday.")
[1] "This is Thursday."
Figure from https://moderndive.netlify.app/

Figure 1: Figure from https://moderndive.netlify.app/

Use Projects

I strongly recommend you create an RStudio project for this course, and use separate projects for your future research/analysis projects. It sets working directory automatically and can save you a lot of troubles.

To create a project, go to File, New Project..., select “New Directory”, “New Project”, and then type in the name of a new folder you want to create for the project as well as where you want the folder to locate on your computer.

Next time you open RStudio, navigate to the top right and find the project you want to work on

Tools –> Global Options –>

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

Note: R is case sensitive. So Cars and cars are different.

summary(cars[-(1:4), ])

YAML options

Chunk options

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Install packages

tweetrmd::include_tweet("https://twitter.com/visnut/status/1248087845589274624")

Check out https://rladiessydney.org/courses/ryouwithme/01-basicbasics-2/

# Install the tidyverse "meta" package
# install.packages("tidyverse")
# Install the here package
# install.packages("here")

Load a package

Tip 1: Try the (PC) Ctrl + Alt + I/(Mac) Cmd + Option + I shortcut for a new code chunk

Tip 2: Use Tab for code completeion

Tip 3: Use Ctrl + Enter/(Mac) Cmd + Return for running a line of R code

Tip 4: Set message = FALSE to suppress messages in loading packages

# Load tidyverse

# Load here

Data Frame

# Load Aids2 data
data("Aids2", package = "MASS")
# Extract one column

# Extract column by index (same as last line)

# Extract two rows

# Compute the mean and sd, and chain them together

# Correlation matrix with psych::pairs.panel()

# Find out what a function does (use `?function_name`, e.g., `?pairs.panel`)

Basic Markdown Elements

From RStudio, click Help –> Markdown Quick Reference

Italic and bolded texts

This is italic

Lists (Ordered and Unordered)

Equations (LaTeX)

Inline: The correlation between \(a = b + c + \tau\)

Display:

\[a = b + c + \tau\]

Cheatsheet

More detailed cheatsheet: https://raw.githubusercontent.com/rstudio/cheatsheets/main/rmarkdown.pdf


Exercise

  1. Download the Rmd file for the exercise on Blackboard
  2. Change the name on line 3 to yours.
  3. Complete the following in this R Markdown document:
    1. Copy the following LaTeX equation to below: \Delta K = \frac{1}{2} mv^2_i. How does this say about writing Greek letters, fractions, and subscripts/superscripts in LaTeX? \[[Insert equation here]\]

    2. Run the following. You’ll need to remove eval = FALSE so that it runs. Write down what each line of the following code chunk does.

      # Install and load the knitr package first; otherwise it won't run
       theta <- rbeta(1000, shape1 = 2, shape2 = 2)
       c(mean = mean(theta), median = median(theta))
       knitr::kable(data.frame(mean = mean(theta), median = median(theta)))
       
    3. Run the following. You’ll need to remove eval = FALSE so that it runs. Find out what this code chunk does.

      pacman::p_load(ggplot2)
       ggplot(data.frame(theta = theta), aes(x = theta)) +
         geom_histogram(bins = 15)
       ggplot(data.frame(theta = theta), aes(x = theta)) +
         geom_density(bw = "SJ")
       
    4. Add a code chunk below to show the output of running sessionInfo(), which prints out the session information of your computer. Make the code chunk to show only the output, but not the code.

    5. Knit the document to HTML, PDF, and Word. If you run into an error when knitting to any one of the formats, record the error message. Which format do you prefer? [Note: You may be prompted to install the tinytex package for PDF output.]

    6. Go to the top of this Rmd file, and change the part inside YAML

      output:
        html_document: default

      to

      output:
        html_document: 
            toc: TRUE
            toc_float: TRUE

      Knit the document again. What does it do?

    7. Submit the knitted document to Blackboard in your preferred format (HTML, PDF, or WORD)

Last updated

[1] "January 13, 2022"

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY-NC-SA 4.0. Source code is available at https://github.com/marklhc/20221-psyc573-usc, unless otherwise noted. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".