Introduction to R


To download this RMarkdown file, go to:

Click “Download” and save the RMarkdown (.Rmd) file in the same folder as your RStudio project

Workshop Overview

Teaching: 40 minutes
Exercises: 10 minutes

Guiding Questions:

What data types are available in R? What is an object? How can values be initially assigned to variables of different data types?
What arithmetic and logical operators can be used?
How can subsets be extracted from vectors?
How does R treat missing values?
How can we deal with missing values in R?

Lesson Objectives:

Define the following terms as they relate to R: object, assign, call, function, arguments, options.
Assign values to objects in R.
Learn how to name objects.
Use comments to inform script.
Solve simple arithmetic operations in R.
Call functions and use arguments to change their default options.
Inspect the content of vectors and manipulate their content.

Running code in R

There are two main ways of interacting with R: by using the console or by using script files (plain text files that contain your code). The console pane (in RStudio, the bottom left panel) is the place where commands written in the R language can be typed and executed immediately by the computer. It is also where the results will be shown for commands that have been executed. You can type commands directly into the console and press Enter to execute those commands, but they will be forgotten when you close the session.

Because we want our code and workflow to be reproducible, it is better to type the commands we want in the script editor and save the script. This way, there is a complete record of what we did, and anyone (including our future selves!) can easily replicate the results on their computer.

RStudio allows you to execute commands directly from the script editor by using the Ctrl + Enter shortcut (on Mac, Cmd + Return will work). The command on the current line in the script (indicated by the cursor) or all of the commands in selected text will be sent to the console and executed when you press Ctrl + Enter. If there is information in the console you do not need anymore, you can clear it with Ctrl + L. You can find other keyboard shortcuts in this RStudio cheatsheet about the RStudio IDE.

Using R as a calculator

The simplest thing you could do with R is to do arithmetic.

Practice: Enter each of the following commands and confirm that the response is the correct answer.

1 + 2 
18.5 - 7.21
3 %% 2 ## what is this doing?

Creating objects

These operations, however, are not very interesting. To do more useful things in R, we need to assign values to an object. To create an object, we tell R the object’s name, followed by an assignment arrow (<-), and finally the value of the object. This would look something like this:

x <- 6

Once we execute/run this line of code, we notice that a new object appears in our environment window. This window shows all of the objects that