Interactive RStudio

RStudio can be used to run code blocks interactively and display the results, allowing you to preview what your knitted file will look like. You have two easy methods available to you for running the code in a code block. The graphical way is to click the green arrow located on the far-right side of a code block. The keyboard shortcut is place your cursor inside the block and then press Ctrl+Shift+Enter all together. The image below illustrates:

Use one of these methods whenever you want to run the code within a block.

Setup chunks

When you are given an RMarkdown template file, it will frequently have a setup code block at the top of the page, much like the one below. These chunks will configure the knitting procedure, which controls how your output documents will look. Often, they will also load the libraries you will need to complete an exercise or assignment. If you reopen a file after restarting RStudio or switching projects, you should always run this block first.

Give it a try, run the block below.

# DO NOT ALTER THIS CHUNK
knitr::opts_chunk$set(
  echo = TRUE,
  eval = TRUE,
  fig.width = 5,
  fig.asp = 0.618,
  out.width = "70%",
  dpi = 120,
  fig.align = "center",
  cache = FALSE
)
# Load required packages
suppressPackageStartupMessages(library(tidyverse))

If you didn’t get an error, then excellent! If so, then you need to complete the RStudio Server Initial Configuration first. If you need help, you can leave a post on Slack.

Demo: The mpg dataset

Viewing the dataset

When loading tidyverse, several practice datasets are automatically loaded, one of which is the mpg dataset. It’s good practice to start by looking at the dataset and getting familiar with the different columns and rows. You can do this within RStudio, try running the code block below:

mpg

You can also read more about the dataset by running:

?mpg

in the Console window.

Question

What is the data contained within the mpg dataset?

Answer

Make a scatterplot

It’s very easy to make a scatterplot in R using the ggplot2 library. This is the library you will read about in Chapter 3 of R for Data Science. Let’s use it to plot each car’s highway fuel efficiency (hwy) as a function of the engine size (displ). The code block below will make this plot, try running it!

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy))