Let’s get familiar with R

In this section we will investigate the following questions: [[ How does R understand data? ]]

  1. How to use this script and R
  2. Creating objects and using logicals
  3. Sequences and vectors (1-D)
  4. Data frames, basic data manipulation (subsetting, renaming, joining), and finding help for using functions

Step 1: How to use this R script

A script is a text document that contains instructions and commands The # symbol is used to leave comments, which R will not try to interpret as a command.

The console (below) is for submitting commands to be interpreted in R. To run a command in the console, you can copy+paste it into the console and press enter.

Copy and paste the following into the console and run it:

> print("the instructor's name is Sydney")  
[1] "the instructor's name is Sydney"

Run a single line of your script in the console by placing your cursor on the line you want to submit and use your cursor to press the “Run” button at the top right. You can also use the shortcut key strokes cmd+enter (mac) or ctrl+enter (PC) to run a single line at a time.

The two other most important keyboard shortcuts that you’ll want to use are the Tab key to auto-complete your typing at the command line and ctrl+up arrow or cmd+up arrow to access the most recently typed commands.

You can also select only part of a line to have it run on the console.

Let’s do an exercise:

Exercise 1: Use the function print to print the sentence

“my name is ____”.

> print("my name is _____")
[1] "my name is _____"

R can also be used to perform calculations, such as the following:

> 5+1/3
[1] 5.333333

What rules does R apply for the order of operations and how do you find out?

Let’s modify the statement above to see if adding parentheses changes the result:

> (5+1)/3
[1] 2

Does it matter if there are spaces added into this?

>  ( 5 + 1 ) / 3
[1] 2

That shows us that the spaces did not matter for the calculation.

R also has some pre-defined matematical terms that you can use, such as pi.

What is pi times pi ?

> pi*pi
[1] 9.869604
> pi^2   # this does the same thing because ^ is, here, interpreted as "taken to the exponent"
[1] 9.869604

Step 2: Creating objects and using logicals

Objects are like shortcuts. They are a way to store data without having to re-type them. By virtue, objects are only created once something has been assigned to them. Anything can be stored in an object, including figures! Let’s repeat our simple math calculation above, this time using objects. If we want to calculate (5+1)/3 using objects, it needs to look like this: (a+b)/c The objects a, b, and c do not exist yet, so we need to assign values to them in order to create them. R interprets the less than symbol and dash as “assign”. So we need to do the following:

> a <- 5  # assign the number 5 to a
> b <- 1  # assign number 1 to b
> c = 3   # we can also use `=` to assign 3 to c. But `<-` is the preferred assignment
>         # operator as `=` is used to call arguments in function calls.

As you are assigning these numbers to objects, they appear in your environment (top right). These objects are not being saved to a hard drive, they are stored in memory of your computer only.

NOTE if you assign something to an object that already exists, R will do what you tell it and overwrite that obect with the new assignment.

Now we can execute our calculation using objects instead of numbers. Try it!

> (a+b)/c
[1] 2

Avoid creating object names that start with a number because R will look at the first character and try to interpret the entire name as a mathematical term. Try this:

> #2foxes <- 1   

The error here tells us that something went wrong and R cannot proceed.

If we want to assign (a+b)/c to a new object called answer – what will the object contain? Find out:

> answer <- (a+b)/c

Take a look at the object answer by typing the name into the command line:

> answer
[1] 2

What would you get if you multiplied answer by 2?

> answer*2
[1] 4

We can also use logical operations in R. The answer to a logical question is always TRUE or FALSE. Is a greater than b?

> a > b # You can look at the Values on your right to check the answer.
[1] TRUE

Is b greater than 10?

> b > 10
[1] FALSE

Is b + c greater than a?

> b + c > a 
[1] FALSE

R will first evaluate the algebraic operation (+) and then evaluate the
logical operation (>). So, we don’t need to use (b+c) > a. Is a equal to 7?

> a = 7 

Oops! We did not get any answer. What went wrong? Let’s print a.

> a
[1] 7

a = 7 changed the value of a to ‘7’. So, how do we find if a is equal to ‘7’?

> a == 7 # We need to put two '=' signs to check equality.
[1] TRUE

Is a not equal to ‘7’?

> a != 7 
[1] FALSE

Are both a and b greater than c?

> (a > c) & (b > c) 
[1] FALSE

Is either a or b greater than c?

> (a > c) | (b > c)
[1] TRUE

The examples above dealt with numeric values assigned to objects. We can also store character data in objects. We need to place the character data (words, phrases, etc.) inside quotation marks, otherwise R will try to interpret the character data as an object and will produce an error.

Let’s use my name for this exercise. Let’s create two objects, one for my first name and another for my last name.

> first.name <- "Sydney"
> last.name <- 'Everhart'  # Single quotes work too!

We now have those two objects. Let’s look at them.

> first.name
[1] "Sydney"
> last.name
[1] "Everhart"

Since we each have a first name and a family name, let’s do another exercise.

Exercise 2: Modify the objects first.name and last.name so that

instead of my name, they contain your name.

> first.name <- "____"  # Replace ____ with your own name
> last.name <- "____"

Did this work? Let’s look at the two objects:

> first.name
[1] "____"
> Last.name
Error in eval(expr, envir, enclos): object 'Last.name' not found

Oops! What went wrong? R is case-sensitive, so last.name is interpreted differently than Last.name. Let’s try again:

> first.name
[1] "____"
> last.name # It works!
[1] "____"

Using a function c() we can tell R to combine these two objects. This function will combine values from the first object with the second object and return them as a single observation. Let’s try it:

> c(first.name, last.name)
[1] "____" "____"

Notice how the names are returned inside quotation marks, which tells us that these are interpreted as character data in R. You’ll also notice that each name is placed inside quotes and that’s because c() combined names into a single vector that contains two elements, your first and your last name. This brings us to the next step in our introduction, vectors.

Step 3: Vectors and sequences

Up to here, the objects we’ve created only contained a single element. You can store more than one element in a 1-dimensional object of unlimited length. Let’s create an object that is a vector of our first and last names using the two objects that we created previously.

Avoid re-typing your commands. Since the last command that we ran contained what we want, we can simply use the up arrow to access the most recently submitted command and modify it. You can also access the History tab in the top right panel of RStudio or, at the command line, access a list of the most recent commands using the cmd + up arrow OR the ctrl + up arrow.

> name <- c(first.name, last.name)

We can inspect this object by typing name at the command line. We can inspect the structure of this object using the function str() on name.

> str(name)
 chr [1:2] "____" "____"

This shows us that this is a vector because the elements in it are ordered from 1 to 2 as shown by the [1:2]. This also tells us that this list is a character list, which is indicated by the chr label. We also see the two elements in this vector, which is your first and last name.

What is the length of your name? We can find out using the function length()

> length(name)
[1] 2

Let’s compare this to a vector that contains only numeric data. For this example, let’s create three objects to represent today’s date in numbers for the month (08), day (03), and year (2019).

> month <- 08
> day <- 03
> year <- 2019

combine those three objects using the combine function:

> today <- c(month, day, year)

Inspect this object by typing the name today at the command line. You’ll see that R has eliminated the zero that preceeds the 4 and has kept the order we provided for these elements in the vector. Let’s take a look at the structure of today.

> str(today)
 num [1:3] 8 3 2019

You’ll notice that the vector has three elements [1:3] and it contains only numeric data.

Let’s do the same thing using the name August for month and see how that changes our vector. Notice that we are not modifying the object month, we are simply combining our two existing objects with the word “August”.

> c("August", day, year)   
[1] "August" "3"      "2019"  

In this case we didn’t re-assign the object named today. To inspect the structure of this vector, we can wrap the statement within the str() function, as shown below. We also want to inspect the data class (ie. whether numeric or character) using the function class(). Don’t forget to use the up-arrow to access the last like that you ran!

> str(c("August", day, year)) # this shows us the structure of the object
 chr [1:3] "August" "3" "2019"
> class(c("August", day, year))
[1] "character"

Notice how R is trying to keep our data organized according to type. Rather than coding this vector as containing numbers and characters, it has decided that because it can’t call everything in our vector a number that it will call everything characters. This process is called coercion.

Let’s say we wanted to create a table that showed every date this month:

  day   month   year
  1     3       2019
  2     3       2019
  3     3       2019
  ...

We know there are 31 days in the month, so we can modify the object day to contain all of the 31 days in this month. Instead of typing each number out by hand, we can place a colon (:) between 1 and 31, which is a shortcut in R for creating sequences of numbers.

> 1:31
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
[24] 24 25 26 27 28 29 30 31

You see at in the console that this created a sequence of 31 numbers from 1 to 31. Let’s go ahead and assign this to the object day.

> day <- 1:31

For the objects month and year, we don’t need to modify them, however, we want to repeat each of them a total of 31 times because we need to repeat each, once for each day.

We can easily repeat the number 8 a total of 31 times using the function rep(), specifying how many times we should repeat this object. Let’s assign 8 to month and modify the object month to contain 31 copies.

> month <- 8
> month <- rep(month, times = 31)
> month
 [1] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

Let’s check to make sure that month is correct using the function length():

> length(month)
[1] 31

There are 31 elements in this vector and we can inspect individual elements in the vector based on their ordered position using square brackets:

> month[3] # the number inside the brackets corresponds to location of element in list, not value
[1] 8
> day[3] 
[1] 3

In this case, the 3rd element in month is 8, and the 3rd element in day is 3 which confirms that we created this correctly.

Type day[32] into your R console. What do you get? What does it mean? Ask yourself the question, “Are there any months with 32 days?”

We can create the object year to contain 31 repeats of 2019, however, this time, let’s say we wanted to make sure that this object was always the same length as the number of days we have in a month. Instead of specifying 31, we can simply get that information using the length() function. Here, we’ll replace 31 with length(day), which is equivalent.

> year <- rep(2019, times = length(day))
> year
 [1] 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019
[15] 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019
[29] 2019 2019 2019
> length(year)
[1] 31

We now have three vectors to create our table and they are exactly the same length:

> length(day)
[1] 31
> length(month)
[1] 31
> length(year)
[1] 31

Step 4: Data frames, basic data manipulation, and finding help

Remember that our goal here is to create a table with the columns “month”, “day”, and “year”. First, here’s a quick reminder of what we want this to look like:

  day   month   year
  1     3       2019
  2     3       2019
  3     3       2019
  ...

In order to create a data frame, we can use the command data.frame(). This function will create columns out of vectors that are all the same length. In the function, we just have to specify name of the column and populate it with vector data.

> August <- data.frame(day = day, month = month, year = year)

Let’s inspect this new object in the same way as vectors:

> August
   day month year
1    1     8 2019
2    2     8 2019
3    3     8 2019
4    4     8 2019
5    5     8 2019
6    6     8 2019
7    7     8 2019
8    8     8 2019
9    9     8 2019
10  10     8 2019
11  11     8 2019
12  12     8 2019
13  13     8 2019
14  14     8 2019
15  15     8 2019
16  16     8 2019
17  17     8 2019
18  18     8 2019
19  19     8 2019
20  20     8 2019
21  21     8 2019
22  22     8 2019
23  23     8 2019
24  24     8 2019
25  25     8 2019
26  26     8 2019
27  27     8 2019
28  28     8 2019
29  29     8 2019
30  30     8 2019
31  31     8 2019
> length(August)
[1] 3

Using the length() function, we see it says 3. This is because August has three columns: day, month, and year. A data frame is a two-dimensional object which stores its information in rows and columns.

Because this is a 2-dimensional object, we can inspect the dimensions using the dim() function:

> dim(August)
[1] 31  3

This tells us that we have 31 rows and 3 columns. R also provides the nrow() and ncol() functions to make it easier to remember which is which:

> nrow(August)
[1] 31
> ncol(August)
[1] 3

What happens when we use the str() function?

> str(August)
'data.frame':   31 obs. of  3 variables:
 $ day  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ month: num  8 8 8 8 8 8 8 8 8 8 ...
 $ year : num  2019 2019 2019 2019 2019 ...

We can see that it’s listing the columns we have in our table and showing us how they are represented. Notice the $ to the left of each column name, this is how we access the columns of the data frame:

> August$day
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
[24] 24 25 26 27 28 29 30 31
> August$month
 [1] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
> August$year
 [1] 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019
[15] 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019
[29] 2019 2019 2019

You can see that these are the same as the vectors we created earlier.

Because this object is rather large, we didn’t get to see the top rows of the obect. A quick way to look at the top of the object is with the head() function and if we wanted to look at the bottom, we would use tail().

> head(August)  # if this didn't work, double-check that you spelled the object name correctly
  day month year
1   1     8 2019
2   2     8 2019
3   3     8 2019
4   4     8 2019
5   5     8 2019
6   6     8 2019

Now that we have our table, the question becomes, how do we inspect different elements?

Just like we can inspect the 3rd element in the day vector using day[3], we can also use the brackets to subset a table, the only catch is that we have to use the coordinates of the row(s) and the column(s) we want. We can do this by specifying [row, column]. These are analagous to X and Y Cartesian coordinates. Let’s take a look at the elements in the 3rd row, separately:

> August[3, 1] # day
[1] 3
> August[3, "month"] # you can use characters when the elements are named!
[1] 8
> August[3, 3] # year
[1] 2019
> August[3, -3] # here `-` means all columns except the third (year)
  day month
3   3     8
> August[3, -2] # day and year
  day year
3   3 2019

If we don’t specify a dimension, R will give us the entire contents of that dimension. Let’s look at the row that contains today’s date:

> August[3, ]
  day month year
3   3     8 2019

You can also use this to access just one column of the matrix. Let’s look at month:

> August[, 2]
 [1] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

Notice, however that this result now appears to be a a vector! This is because of a sneaky default option called drop = TRUE. R tries to “help” by removing the dimensions of your data frame if you choose only one column. If you want to keep this as a data frame, you can turn off this option inside the brackets:

> August[, 2, drop = FALSE]
   month
1      8
2      8
3      8
4      8
5      8
6      8
7      8
8      8
9      8
10     8
11     8
12     8
13     8
14     8
15     8
16     8
17     8
18     8
19     8
20     8
21     8
22     8
23     8
24     8
25     8
26     8
27     8
28     8
29     8
30     8
31     8

Now that we’ve inspected the object August, let’s create the same thing for the month of September. How should we do this? One option would be to create new obects for day, month, and year and combine them just like we did for August. What is the simplest method to do this, using the fewest number of steps? We can simply make a copy of August and delete a vector with information about the 31st day. Now that we have two dimensions, we can subset everything in August
except for the 31st row and all the columns of that row.

> September <- August[-31,]

Inspect what we have now:

> str(September)  # we have an extra column
'data.frame':   30 obs. of  3 variables:
 $ day  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ month: num  8 8 8 8 8 8 8 8 8 8 ...
 $ year : num  2019 2019 2019 2019 2019 ...
> tail(September) # we don't have 31 days
   day month year
25  25     8 2019
26  26     8 2019
27  27     8 2019
28  28     8 2019
29  29     8 2019
30  30     8 2019

We need to change the month column so that it says 9 instead of 8, how can we do this? Let’s just look at the column first:

> September$month
 [1] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

We need to add 1 to each of these values, so let’s try that!

> September$month + 1
 [1] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

This worked, so now we just need to replace values in September[,2] with the new expression:

> September$month <- September$month + 1    # Did it work?
> str(September)
'data.frame':   30 obs. of  3 variables:
 $ day  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ month: num  9 9 9 9 9 9 9 9 9 9 ...
 $ year : num  2019 2019 2019 2019 2019 ...

Let’s combine both of these tables into one. R provides two functions that can help us with that called rbind() and cbind(), which bind a data frame with a vector (or another data frame) by rows and columns, respectively. Which one should we use? If you’re unsure, try both!

Exercise 3: Use cbind() and rbind() to figure out the correct

function to stack the tables one below the other.

> cbind(August, September) # Do you think it will work?
Error in data.frame(..., check.names = FALSE): arguments imply differing number of rows: 31, 30

We have an error! R is trying to stack them side by side and is failing to do so because of different number of rows.

> rbind(August, September) # This works!
   day month year
1    1     8 2019
2    2     8 2019
3    3     8 2019
4    4     8 2019
5    5     8 2019
6    6     8 2019
7    7     8 2019
8    8     8 2019
9    9     8 2019
10  10     8 2019
11  11     8 2019
12  12     8 2019
13  13     8 2019
14  14     8 2019
15  15     8 2019
16  16     8 2019
17  17     8 2019
18  18     8 2019
19  19     8 2019
20  20     8 2019
21  21     8 2019
22  22     8 2019
23  23     8 2019
24  24     8 2019
25  25     8 2019
26  26     8 2019
27  27     8 2019
28  28     8 2019
29  29     8 2019
30  30     8 2019
31  31     8 2019
32   1     9 2019
33   2     9 2019
34   3     9 2019
35   4     9 2019
36   5     9 2019
37   6     9 2019
38   7     9 2019
39   8     9 2019
40   9     9 2019
41  10     9 2019
42  11     9 2019
43  12     9 2019
44  13     9 2019
45  14     9 2019
46  15     9 2019
47  16     9 2019
48  17     9 2019
49  18     9 2019
50  19     9 2019
51  20     9 2019
52  21     9 2019
53  22     9 2019
54  23     9 2019
55  24     9 2019
56  25     9 2019
57  26     9 2019
58  27     9 2019
59  28     9 2019
60  29     9 2019
61  30     9 2019
> Fall <- rbind(August, September)

Inspect this object to ensure it was made correctly.

> str(Fall)
'data.frame':   61 obs. of  3 variables:
 $ day  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ month: num  8 8 8 8 8 8 8 8 8 8 ...
 $ year : num  2019 2019 2019 2019 2019 ...
> head(Fall)
  day month year
1   1     8 2019
2   2     8 2019
3   3     8 2019
4   4     8 2019
5   5     8 2019
6   6     8 2019
> tail(Fall)
   day month year
56  25     9 2019
57  26     9 2019
58  27     9 2019
59  28     9 2019
60  29     9 2019
61  30     9 2019

We now have a new object Fall that contains only numeric data. Let’s revise this object so that it uses names for the month instead of numbers. We want it to look like this:

  day   month   year  
  1     "August"   2019  
  2     "August"   2019  
  3     "August"   2019
  ...

Months need to be changed from the number 3 to “August” and from 4 to “September” in the second column. Let’s first look at the month column.

> Fall$month
 [1] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9
[36] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

We want to specify only the cells in this list that are 3. We know that rows 1 to 31 contain 3’s and the rest contain 4’s, which means we can inspect those rows in the object Fall:

> Fall[1:31, "month"]     # August
 [1] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
> Fall[-c(1:31), "month"] # September
 [1] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

Notice that we used -c(1:31), what do you think this is doing? Why would this give us the values for the month of September?

We can use the ifelse() function to replace the values in our column. How do we use this function? A good first step to figuring out how you can use a function is to look at its help page. The way you can do that is by typing
either help("function_name") or ?function_name.

> ?ifelse

Exercise 4: Type ?ifelse and answer these three questions:

1. What does it do? (Description)

2. What are the arguments? (Usage/Arguments)

3. What does it return? (Value)

In order to use ifelse, we will need to provide three things:

  1. A logical question about the elements of an object : Fall$month == 8
  2. Values for TRUE elements : “August”
  3. Values for FALSE elements : “September”
> ifelse(Fall$month == 8, yes = "August", no = "September")
 [1] "August"    "August"    "August"    "August"    "August"   
 [6] "August"    "August"    "August"    "August"    "August"   
[11] "August"    "August"    "August"    "August"    "August"   
[16] "August"    "August"    "August"    "August"    "August"   
[21] "August"    "August"    "August"    "August"    "August"   
[26] "August"    "August"    "August"    "August"    "August"   
[31] "August"    "September" "September" "September" "September"
[36] "September" "September" "September" "September" "September"
[41] "September" "September" "September" "September" "September"
[46] "September" "September" "September" "September" "September"
[51] "September" "September" "September" "September" "September"
[56] "September" "September" "September" "September" "September"
[61] "September"
> Fall$month <- ifelse(Fall$month == 8, yes = "August", no = "September")

Notice that we had to use == to indicate equality. This is so that R doesn’t get confused and assume we are using the argument assignment, =. Now, let’s inspect Fall.

> str(Fall)
'data.frame':   61 obs. of  3 variables:
 $ day  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ month: chr  "August" "August" "August" "August" ...
 $ year : num  2019 2019 2019 2019 2019 ...
> head(Fall)
  day  month year
1   1 August 2019
2   2 August 2019
3   3 August 2019
4   4 August 2019
5   5 August 2019
6   6 August 2019
> tail(Fall)
   day     month year
56  25 September 2019
57  26 September 2019
58  27 September 2019
59  28 September 2019
60  29 September 2019
61  30 September 2019

Let’s change first letter of every column name to uppercase i.e., replace
“day” with “Day” and so on. We can do this using colnames() function.

> colnames(Fall) # Current column names
[1] "day"   "month" "year" 
> colnames(Fall) <- c("Day", "Month", "Year") # New column names

Let’s inspect Fall again.

> str(Fall)
'data.frame':   61 obs. of  3 variables:
 $ Day  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Month: chr  "August" "August" "August" "August" ...
 $ Year : num  2019 2019 2019 2019 2019 ...
> head(Fall)
  Day  Month Year
1   1 August 2019
2   2 August 2019
3   3 August 2019
4   4 August 2019
5   5 August 2019
6   6 August 2019

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.