# 2 - Vectors ------------------------------------------------------------------
# 2.1 - Single-item vectors (and quoting)
# Challenge 1
# Which of the following options will produce an error?
# (There may be more than one.)
# A) number1 <- "42"
# number1
# B) color <- blue
# color
# C) animal <- "djfhjkhkjkhCGT"
# animal
# D) number2 <- 1e6
# number2
# 2.2 - Multi-item vectors
# Challenge 2
# Which items does the vector birds contain after running the code above?
# A) cardinal and chickadee
# B) cardinal, chickadee, and bald eagle
# 2.3 - Vectorization
# Challenge 3
# A) Create a vector `x` with whole numbers 1 through 13,
# then print the vector to check your results.
x <- ______
______
# B) Subtract 0.5 from each item in `x` and save the result in vector `y`,
# then print the vector to check your results.
y <- ______
______
# 2.4 - Exploring vectors
# 3 - Data types ---------------------------------------------------------------
# 3.1 - R's main data types
# 3.2 - A vector can only contain one data type
# Challenge 4
# In each line below, what do you think the data type will be, if any?
# Try it out and see if you were right.
# typeof("TRUE")
# typeof(banana)
# typeof(c(2, 6, "3"))
# 3.3 - Manual type conversionVectors and data types
1 Introduction
1.1 What we’ll cover
In this session, you will learn about some of the ways that R stores data. Specifically, we will cover vectors and data types.
Vectors are the simplest of the R “data structures”, object types that R can store data in.
Data types are how R distinguishes between different kinds of data like numbers and text. We’ll talk about the 4 main data types:
character,integer,double, andlogical.
Having a solid understanding of these foundational R concepts will help you avoid many common pitfalls when working with R.
1.2 Setting up
To make it easier to keep track of what we do, we’ll write our code in a script:
Open a new R script: Click the
+symbol in the top toolbar, then clickR Script1.Save the script straight away as
data-structures.R. You can save it anywhere you like, but ideally in a folder you made for this workshop.If you want a pre-made skeleton with section headers as comments in your script, copy-and-paste the following into your script:
Section headers for your script (Click to expand)
2 Vectors
A vector in R is essentially a collection of one or more items.
2.1 Single-item vectors (and quoting)
Vectors can consist of just a single item, so each of the two lines of code below creates a vector:
vector1 <- 8
vector2 <- "panda"In the second example, "panda" is a character string (or simply “string”):
"panda"constitutes one item, not 5 (its number of letters).- Unlike when dealing with numbers, we have to quote the string.2
- This doesn’t mean the quotes are part of the string itself: they are just a way to tell R that it is a string.
Character strings need to be quoted because without quotes, R interprets them as names of objects. For example, since vector1 and vector2 are objects, we refer to them without quotes:
# Print the values of the two vectors to screen:
vector1[1] 8
vector2[1] "panda"
Meanwhile, the code below doesn’t work because there is no object called panda:
vector_fail <- pandaError:
! object 'panda' not found
Challenge 1: Quoting
Which of the following options will produce an error? (There may be more than one.)
First think about it, then click the Run Code button to check your answer. Afterwards, you can also click the Explanation tab to see why.
The only option that will produce an error is the second, color <- blue. Here, blue needs to be quoted as "blue". Without the quotes, R looks for an object called blue, and returns an error because no such object exists.
color <- blueError:
! object 'blue' not found
As for the other options:
Even though
"42"is a number, it is still a valid string because it is quoted:number1 <- "42" number1[1] "42"Even though
"djfhjkhkjkhCGT"is gibberish, it is still a valid string because it is quoted:animal <- "djfhjkhkjkhCGT" animal[1] "djfhjkhkjkhCGT"1e6is a valid number in scientific notation, and R will interpret it as 1 million:number2 <- 1e6 number2[1] 1e+06
2.2 Multi-item vectors
A common way to make vectors with multiple items is with the c (combine) function:
num_vec <- c(2, 6, 3, 41)
num_vec[1] 2 6 3 41
The c() function can also add items to a vector you already have. Below, we first create a vector, and then use that vector as an argument to the c() function:
birds <- c("cardinal", "chickadee")
birds[1] "cardinal" "chickadee"
c(birds, "bald eagle")[1] "cardinal" "chickadee" "bald eagle"
Challenge 2: Changing vectors
Click on one of the options below to make your selection, and the page will tell you whether it is correct. You can then also click the Explanation tab for more information.
Which items does the vector birds contain after running the code above?
The answer is A) cardinal and chickadee.
The c() function does not modify the original vector, but instead returns a new vector with the additional item.
Since we didn’t save the new vector to an object, the original vector birds remains unchanged, and bald eagle is not added to it.
To add the new item to the original vector, we would save the result of c() back to birds:
birds <- c(birds, "bald eagle")
birds[1] "cardinal" "chickadee" "bald eagle"
Vectors containing a series of numbers are often useful, and the : operator is a handy shortcut for making series of whole numbers (integers):
series_vec <- 1:10
series_vec [1] 1 2 3 4 5 6 7 8 9 10
Another example:
15:20[1] 15 16 17 18 19 20
2.3 Vectorization
Consider the output of these commands:
series_vec * 2 [1] 2 4 6 8 10 12 14 16 18 20
series_vec + 1 [1] 2 3 4 5 6 7 8 9 10 11
In the first example, every individual item in series_vec was multiplied by 2. Similarly, in the second example, every individual item in series_vec was increased by 1.
This behavior, where an operation is automatically applied to every item of a vector, is called “vectorization” — a key feature of the R language!
Challenge 3: Vectorization
Replace the blanks ______ in the code below with the correct code, then click Run Code to have your answer checked:
- Create a vector
xwith whole numbers 1 through 13, then print the vector to check your results.
# Create a vector `x` with whole numbers 1 through 13.
x <- 1:13
# Print vector x to check your results.
x [1] 1 2 3 4 5 6 7 8 9 10 11 12 13
- Subtract 0.5 from each item in
xand save the result in vectory, then print the vector to check your results.
# Subtract 0.5 from each item in x and save the result in vector y
y <- x - 0.5
# Print vector y
y [1] 0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.5 12.5
2.4 Exploring vectors
R has many functions that provide information about vectors and other types of objects, such as:
Get the number of items with
length():length(series_vec)[1] 10See the first few items with
head()(or the last few withtail()):By default, it prints the first 6 items:
head(series_vec)[1] 1 2 3 4 5 6You can specify the number of items with the
nargument:head(series_vec, n = 2)[1] 1 2
Get arithmetic summaries like
mean()for vectors with numbers:# mean() will compute the mean (average) across all items mean(series_vec)[1] 5.5
3 Data types
3.1 R’s main data types
R distinguishes between different kinds of data, such as character strings and numbers, with several pre-defined “data types”. Its behavior in various operations depends heavily on the data type.
For example, R refuses to perform mathematical operations on character strings, so the code below will return an error:
"valerion" * 5Error in `"valerion" * 5`:
! non-numeric argument to binary operator
We can ask what the data type of something is using the typeof() function:
typeof("valerion")[1] "character"
R has automatically set the data type of "valerion" to character, i.e. a character string.
Note that while the character data type most commonly contains letters, anything that is placed between quotes ("...") will be interpreted as this data type — even plain numbers:
typeof("5")[1] "character"
Besides character, three other common data types are:
double(sometimes referred to asnumeric) — numbers that can have decimal points:typeof(3.14)[1] "double"integer— whole numbers only:typeof(1:3)[1] "integer"logical(eitherTRUEorFALSE, unquoted!):typeof(TRUE)[1] "logical"
3.2 A vector can only contain one data type
A vector can only be composed of a single data type. As we saw above, R silently picks the “best-fitting” data type when you create a vector.
Challenge 4: Data types
In each line below, what do you think the data type will be, if any? Try it out and see if you were right.
"TRUE"ischaracter(and notlogical) because of the quotes around it:typeof("TRUE")[1] "character"
Recall the earlier example: this returns an error because the object
bananadoes not exist. Any unquoted string (that is not a special keyword likeTRUEandFALSE) is interpreted as a reference to an object in R.typeof(banana)Error: ! object 'banana' not found
This produces a
charactervector, and we’ll talk about why right below this challenge:typeof(c(2, 6, "3"))[1] "character"
R’s behavior of returning a character vector for c(2, 6, "3") in the challenge above is called type coercion. More generally, R forcibly converts any non-conforming items to the type it has chosen for a vector.
Type coercion can be the source of many surprises, and is one reason you need to be aware of data types and R’s behavior around them.
3.3 Manual type conversion
You are not at the mercy of whatever R decides to do automatically: you can also convert vectors yourself, using the as. group of functions:
Try to use RStudio’s auto-complete functionality here: type “as.” and then press the Tab key.
as.integer(c("0", "2"))[1] 0 2
as.character(c(0, 2))[1] "0" "2"
As you may have guessed, though, not all type conversions are possible — for example:
as.double("kiwi")Warning: NAs introduced by coercion
[1] NA
NA is R’s way of denoting missing data – see this bonus section for more.
That’s it for this session! After lunch, we’ll learn to manipulate and summarize data frames using a real dataset with statistics such as population size for many countries over time.