5 Getting started with R and RStudio
Abstract
This chapter provides readers with instructions on installing the software necessary to complete any of the subsequent walkthrough chapters. Readers who are familiar with R and RStudio, including installing and loading packages in R, may find this to be a helpful review or may prefer to skip the chapter entirely. This chapter also covers the basics of writing and running code in RStudio. It closes with an introduction to using the {swirl} package. It is designed to help you get started using R and RStudio, assuming no prior use of either.
This chapter, the following chapter (on Foundational Skills), and each of the walkthrough chapters include an overview of the topics emphasized and the functions introduced in the chapter.
5.1 Topics emphasized
For all of the topics emphasized sections, we indicate topics that are unique to each chapter. However, there is a great deal of overlap between chapters. For example, visualizing data is regularly used as a part of carrying out a data science project in education. Therefore, consider these topics emphasized to be the particular focus of the chapters they reference.
- Installing R, RStudio, and R packages
5.2 Functions introduced
For the “functions introduced” sections, notice that some functions look different than others. For example, pak::pak()
is different than install.packages()
.
The pak()
function comes from a specific package (which we’ll discuss in great depth in this and the following chapter). If you had a hunch that this function comes from the pak
package, you’d be correct. The ::
symbols (described more in Chapter 6) mean that the function comes from a particular package. That way, you’ll know which package you will need if you want to use the function. Not sure what some of these terms mean quite yet? Read on in this chapter to learn more about installing and using packages.
install.packages()
pak::pak()
library()
print()
readr::read_csv()
here::here()
swirl::swirl()
swirl::install_course()
5.3 Chapter overview
This chapter is designed to help you to get started using R and RStudio, assuming no prior use of either.
We will be covering the following topics in this chapter:
- Downloading R and RStudio
- RStudio layout and customization
- Writing and running code in RStudio
- Installing the {dataedu} package
- Exploring R with the {swirl} package
If you already have experience using R and RStudio, you may find some of the contents of this chapter to be a refresher—or as a chance to learn a new things about getting set up. If you are looking to get started with the basics of data loading and manipulation using the {tidyverse} (Wickham et al., 2019) right now, consider reading this chapter and then starting Chapter 6, which covers foundational skills.
5.4 Downloading R and RStudio
First, you will need to download the latest versions of R (R Core Team, 2019) and RStudio (RStudio Team, 2015). R is a free environment for statistical computing and graphics using the programming language R. RStudio is a set of integrated tools created by Posit that allow for a more user-friendly experience for using R.
Although you will likely use RStudio as your main console and editor, you must first install R as RStudio uses R behind the scenes. Both R and RStudio are freely available, cross-platform, and open-source.
5.4.1 To download R:
- Visit CRAN (https://cran.r-project.org/) to download R
- Find your operating system (Mac, Windows, or Linux)
- Select the “latest release” on the page for your operating system
- Download and install the application
Don’t worry—you won’t mess anything up if you download the wrong file.
5.4.2 To download RStudio:
- Visit Posit’s website (https://posit.co/downloads/) to download RStudio
- Under the column called “RStudio Desktop”, click “Download RStudio”
- Click “Download RStudio” on the RStudio Desktop page, which should automatically detect your operating system
If you have problems installing these, consider the Data Carpentry page (https://datacarpentry.org/R-ecology-lesson/) and then reach out for help. Another excellent place to get help is the Posit Community forum (https://forum.posit.co/).
5.5 RStudio layout and customization: getting to know R through RStudio
Now that we’ve installed both R and RStudio, we will be accessing R through RStudio. One of the most reliable ways to tell if you’re opening R or RStudio is to look at the icons:
Whenever we want to work with R, we’ll open RStudio. RStudio interfaces directly with R, and is an Integrated Development Environment (IDE). This means that RStudio comes with built-in features that make using R easier. If you’d like more information on the difference between R and RStudio, consider reading the “Getting Started” section of the Modern Dive (https://moderndive.com/1-getting-started.html#) textbook (Ismay & Kim, 2019).
You do not have to use RStudio to access R, and many people don’t!
Other IDEs that work with R include:
- Positron (https://github.com/posit-dev/positron/releases)
- Jupyter Notebook (https://jupyter.org/)
- Visual Studio Code (https://code.visualstudio.com/)
- VIM (https://github.com/jalvesaq/Nvim-R)
- IntelliJ IDEA (https://plugins.jetbrains.com/plugin/6632-r-language-for-intellij)
- EMACS Speaks Statistics (ESS) (https://ess.r-project.org/)
This is a non-exhaustive list and most of these options require a good deal of familiarity with a given IDE.
We bring up alternative IDEs—particularly ESS—because RStudio, as of this writing, is not fully accessible for learners who use screen readers. We have chosen to use RStudio in this text in order to standardize the experience, but we encourage you to choose the IDE that best suits your needs.
5.5.1 RStudio layout
When we open RStudio for the first time, we should see something similar to this:
We’ll refer to these three “panes” as the “Console pane”, the “Environment pane”, and the “Files pane”.
The large square on the left is the Console pane, the square in the top right is the Environment pane, and the square in the bottom right is the Files pane.
As you work with R more, you’ll find yourself using the tabs within each of the panes.
When you create a new file, such as an R script, an R Markdown file, or a Shiny app, RStudio will open a fourth pane, known as the “Source pane”. The Source pane should show up as a square in the top left. You can open an .R
script in the Source pane by going to “File”, selecting “New File”, and then selecting “R Script”:
You do not need to do anything specific with this file, but we encourage you to experiment with it if you would like.
5.5.2 Customizing RStudio
One of the balances to strike in this text is a balance between best practices in your workflow (how you’ll use R in your projects) and your R code. A best practice for your workflow is to ensure that you’re starting with a blank slate every time you open R through RStudio.
To accomplish this, go to “Tools”, and select “Global Options” from the dropdown menu.
The “General” tab will open, with several checkboxes selected and unselected. It’s important to select “Never” next to the “Save workspace to .RData on exit:” prompt. After selecting “Never”, go through and check and uncheck boxes so that your General tab looks like this:
Last, click on the “Appearance” tab from within Global Options. From here you can select your RStudio Font, Font Size, and Theme. Go through the options and select an appearance that works best for you, and know that you can always come back and change it.
5.5.3 Minimized and missing panes
If, at any point, you find that one of your panes has disappeared, one of two things has likely happened:
- A pane has been minimized
- A pane has been closed
Look at the Environment pane as an example. If the Environment pane has been minimized, we’ll see something like this:
You’ll know that the Environment pane has been minimized because, although we can see the pane headers in the top right, you can’t see the information within the Environment pane. To fix this, click on the icon of two squares in the top right of the Environment pane. If you click on the icon of the large square in the top right of the Environment pane, you’ll maximize the Environment pane and minimize the Files pane. This is not preferred, since in general you’ll want to see all the panes at once.
If the Environment pane has somehow been closed, you can recover it by going to the “View” menu, selecting “Panes”, and then selecting “Pane Layout”, like so:
When you select Pane Layout, you’ll see this:
From here, you can select which tabs you’d like to appear within each pane, and you can even change where each pane appears within RStudio. If the Environment Pane had been closed, select it from the Pane Layout in order to re-open it within RStudio.
5.6 Writing and running code in RStudio
Up to this point, you’ve been exploring the RStudio interface and setting up your preferences. Now, you’ll shift to basic coding practices.
In order to run code in R, you need to type your code either in the Console or within an .R
script.
When possible, create an .R
script as you’re learning, as it allows you to type all of your code, add comments, and then save your .R
script for reference. If you work entirely in the Console, anything that you type in the Console will disappear as soon as you restart or close R, and you will not be able to reference it in the future.
5.6.1 Writing code in the console
To run code in the Console, you type your code next to the >
and hit Enter
. Practicing running code in the Console by exploring some basic properties of coding in R.
In the Console, type 3 + 4
and hit Enter
.
You should see the following:
You’ve just used R to add the numbers 3 and 4. R has returned the sum of 3 + 4
on a new line, next to [1]
. The [1]
tells you that there is one row of data.
You can also use R to print out text. Type the following in the Console and hit Enter
:
You should see this in the Console:
There’s one error that you’re likely going to come across, both when running code in the Console as well as in an R script. Explore that error now by running the following code in the Console and hitting Enter
:
Make sure that you left off the closing parenthesis. What you’ll see in the Console is:
When you’re missing a closing parenthesis, R is expecting you to provide more code. You’ll know this because instead of seeing a carat >
in our Console, you see a +
, and R has not returned the expected print statement.
There are two ways to fix this problem:
- Type the closing
)
in the Console and hitEnter
- Hit the
Esc
key
Run this intentional error, and try each of the options above. Compare the output of each, and think about how they’re different. Can you think of when you might want to use one option instead of the other?
5.6.2 Writing code in an R script
There are three main ways to run code in an .R
script:
- Highlight the line(s) of code you’d like to run and press
Ctrl
+Enter
- Highlight the line(s) of code you’d like to run and click the “Run” button in the
R script
pane
- To run every line of code in your file you can press
Ctrl
+Shift
+Enter
Create a new .R
script, or open the one you created earlier in this chapter. Next, type in the following code and run it using each of the options listed above.
print("We're going to use R as a calculator.")
print("First up, addition!")
12 + 8
632 + 41
print("Next, subtraction!")
48 - 6
0.65 - 1.42
Feel free to spend some more time writing and running code within your .R
script, or move on to the next section, where you’ll add comments to our code.
5.6.3 Commenting your code in R
It is considered good practice to comment your code when working in an .R
script. Even if you are the only person working on your code, it’s helpful to write yourself notes about what you were trying to do with a specific piece of code.
Moreover, writing comments in your code as you work through the examples in this book is a great way to reinforce you’re learning.
And remember, comments are ignored by R when running a script, so they will not affect your code or analysis.
To comment out a line of code, place a pound sign (also called an octothorpe) #
in front of the line of code that you want to exclude when you’re running your script.
Be careful when excluding certain lines of code, especially in longer files, as it can be easy to forget where you’ve commented. Rather than commenting out individual lines of code, it is often better to start a new section of code to tinker with until it works as expected.
You can also write comments in line with your code, like this:
#' This will be a short code example.
#' You are not expected to know what this does,
#' nor do you need to try running it on your computer.
library(readr) # Load the readr package
library(here) # Load the here package
data <- read_csv(here("file_path", "file_name.csv")) # Save file_name.csv as data
If you think you’ll be writing more than one line of comments, you can do a pound sign followed by a single quotation mark (#'
). This will continue to comment out lines of text or code each time you hit Enter
. You can delete the #'
on a new line where you want to write code for R to run. This method is useful when you’re writing a long description of what you’re doing in R.
Note: “Commenting” refers to adding in actual text comments, whereas “commenting out” refers to using the pound sign (octothorpe) in front of a line of code so that R ignores it.
You’ll also note the phrase “uncomment code”, which means you should delete or omit the #
or #'
in an example.
5.7 Installing the {dataedu} package
This next section will go over installing the {dataedu} package that’s used throughout this book. This package provides readers with resources for using this book.
The package serves four main functions:
- Mass installation of all the packages used in the book
- Reproducible code for the walkthroughs
- Access to the data used in each of the walkthroughs
- The “dataedu” theme and color palette for reuse
If you feel that you need more information before you’re ready to install the package, you can skip this section. You’ll learn about packages, their installation, and how to load them into R in more depth in Chapter 6.
However, if you’re feeling adventurous, give it a shot by running the code below. Please note that the {dataedu} package requires R version 3.6 or higher to run.
# Install {pak}
install.packages("pak")
# Install the {dataedu} package (requires R version 3.6 or higher)
pak::pak("data-edu/dataedu")
A special note on {tabulizer}:
One of the walkthroughs uses {tabulapdf}, created by ROpenSci to read PDFs.
{tabulapdf} requires the installation of RJava, which can be a tricky process on Mac computers.
Neither {tabulapdf} nor {RJava} are included in mass_install()
. Reading through the notes on the {tabulapdf} GitHub repository if you choose to install it.
5.8 Exploring R with the {swirl} package
If you were able to install the {dataedu} package without problems and you’re eager to start exploring what R can do, supplement your learning through {swirl} (https://swirlstats.com/students.html).
Install {swirl} by running the following code:
{swirl} is a set of packages (see more on packages in Chapter 6) providing an interactive method for learning R by using R in the RStudio Console.
Since you’ve already installed R, RStudio, and the {swirl} package, you can follow the instructions on the {swirl} webpage or run the following code in your Console pane to get started with a beginner-level course in {swirl}:
There are multiple courses available on {swirl}, and you can access them by installing them and then running the swirl()
command in your console.
The authors are not affiliated with {swirl} in any way, nor is {swirl} required to progress through this text. But it is a great resource to keep on your radar!
5.9 Conclusion
Congratulations! At this point in the book, you’ve installed R and RStudio, explored the RStudio IDE, and written some basic code.
At this point, you’re set up to move on to Chapter 6, where you’ll do a deeper dive into projects, packages, and functions, and how those relate to your future data tasks. You’ll also learn about documentation.
Alternatively, if that sounds familiar to you already, feel free to jump ahead to a walkthrough of your choosing.