Course Outline

segmentGetting Started (Don't Skip This Part)

segmentIntroduction to Statistics: A Modeling Approach

segmentPART I: EXPLORING VARIATION

segmentChapter 1  Welcome to Statistics: A Modeling Approach

segmentChapter 2  Understanding Data

segmentChapter 3  Examining Distributions

segmentChapter 4  Explaining Variation

segmentPART II: MODELING VARIATION

segmentChapter 5  A Simple Model

segmentChapter 6  Quantifying Error

segmentChapter 7  Adding an Explanatory Variable to the Model

segmentChapter 8  Models with a Quantitative Explanatory Variable

segmentPART III: EVALUATING MODELS

segmentChapter 9  Distributions of Estimates

segmentChapter 10  Confidence Intervals and Their Uses

segmentChapter 11  Model Comparison with the F Ratio

segmentChapter 12  What You Have Learned

segmentResources
list Introduction to Statistics: A Modeling Approach
Save Your Work In R Objects
Have you ever had an experience where you have forgotten to save your work? It’s a terrible feeling. Saving your work is also important in R. In R, we don’t just do calculations and look at the results on the R console. We usually save the results of the calculations somewhere we can find them later.
Pretty much anything, including the results of any R function, can be saved in an R object. This is accomplished by using an assignment operator, which looks kind of like an arrow (<). You can make up any name you want for an R object. Any combination of upper case letters, lower case letters, numbers, or even a period or underscore can be used in the names of R objects.
Here’s a simple example to show how it’s done. Let’s make up a name for an R object; we will call it myfavoritenumber. Then let’s think of what our favorite number is (say, 20), and save it in the R object. Go ahead and run the code below to see how this works.
# no PEC
# this code will assign the number 20 to the R object myfavoritenumber
myfavoritenumber < 20
# this code prints out myfavoritenumber. Notice that you don't need to use the print() function to print the contents of an R object; you just need to type the name of the object.
myfavoritenumber
# now revise the code to put in your actual favorite number.
#This is an example, but any number should work!
myfavoritenumber < 20
myfavoritenumber
ex() %>% check_object('myfavoritenumber')
ex() %>% check_output_expr("myfavoritenumber")
ex() %>% check_error()
Now remember, R is case sensitive. Try assigning 5 to num and 10 to NUM.
#No PEC
# Assign 5 to num and 10 to NUM
num <
NUM <
# Now write the code to print out the number 10
# Assign 5 to num and 10 to NUM
num < 5
NUM < 10
# Now write print out the number 10
NUM
msg_undefined = "Make sure to define the variable."
msg_incorrect = "Make sure you assign the correct value to the variable."
ex() %>% check_object('num', msg_undefined) %>% check_equal(msg_incorrect)
ex() %>% check_object('NUM', msg_undefined) %>% check_equal(msg_incorrect)
ex() %>% check_output_expr("NUM")
ex() %>% check_error()
success_msg("Fantastic work!")
Vectors
We’ve used R objects so far to store a single number. But in statistics we are dealing with variation, which by definition means more than one, and sometimes many, numbers. An R object can also store a whole set of numbers, called a vector. You can think of a vector as a list of numbers (or values).
The R function c()
can be used to combine a list of individual values into a vector. You could think of the “c” as standing for “combine.” So in the the following code we have created two vectors (we just named them my.vector and my.vector2) and put a list of values into each vector.
#No PEC
#Here is the code to create two vectors my.vector and my.vector2. We just made up those names.
#Run the code and see what happens
my.vector < c(1,2,3,4,5)
my.vector2 < c(10,10,10,10,10)
#Now write some code to print out these two vectors in the R console. Run the code and see what happens.
my.vector < c(1,2,3,4,5)
my.vector2 < c(10,10,10,10,10)
my.vector
my.vector2
ex() %>% check_object('my.vector')
ex() %>% check_object('my.vector2')
ex() %>% check_output_expr("my.vector")
ex() %>% check_output_expr("my.vector2")
ex() %>% check_error()
success_msg("Great! Continue to the next exercise.")
If you ask R to perform an operation on a vector, it will assume that you want to work with the whole vector not just one of the numbers.
So if you want to multiply each number in my.vector by 100, then you can just write my.vector * 100. Try it in the Data Camp window below.
# No PEC
my.vector < c(1,2,3,4,5)
# write code to multiply each number in my.vector by 100
my.vector < c(1,2,3,4,5)
my.vector * 100
ex() %>% check_object("my.vector") %>% check_equal()
ex() %>% check_operator("*") %>% check_result() %>% check_equal()
ex() %>% check_error()
Notice that when you do a calculation with a vector, you’ll get a vector of numbers as the answer, not just a single number.
After you multiply my.vector by 100, what will happen if you print out my.vector? Will you get the original vector (1,2,3,4,5) or one that has the hundreds (100,200,300,400,500)? Try running this code to see what happens.
# No PEC
# Run the code below to see what happens
my.vector < c(1,2,3,4,5)
my.vector * 100
# This will print out my.vector
my.vector
my.vector < c(1,2,3,4,5)
my.vector * 100
my.vector
ex() %>% check_object("my.vector") %>% check_equal(incorrect_msg = "make sure not to change the contents of my.vector")
ex() %>% check_operator("*") %>% check_result() %>% check_equal(incorrect_msg = "make sure to keep the line my.vector * 100")
ex() %>% check_output_expr("my.vector", missing_msg = "did you print my.vector?")
ex() %>% check_error()
success_msg("Nice job!")
Remember, R will do the calculations, but if you want something saved you have to assign it somewhere. Try writing some code to compute my.vector * 100 and then assign the result back into my.vector. If you do this, it will replace the old contents of my.vector with the new contents (i.e., the product of my.vector and 100).
my.vector < c(1,2,3,4,5)
#Write code to save `my.vector * 100` back into `my.vector`
my.vector <
my.vector < my.vector * 100
ex() %>% check_operator("*") %>% check_result() %>% check_equal()
ex() %>% check_object("my.vector")
ex() %>% check_error()
There may be times when you just want to know one of the values in a vector, not all of the values. We can index a position in the vector by using brackets with a number in it like this: [1]
. So if we wanted to print out the contents of the first position in my.vector, we could write my.vector[1]
.
my.vector < c(1,2,3,4,5)
my.vector < my.vector * 100
# Try writing code to index the 4th number in my.vector
# Try writing code to index the 4th number in my.vector
my.vector[4]
ex() %>% check_output_expr("my.vector[4]", missing_msg = "Have you used `[4]` to print out the 4th number in `my.vector`?")
ex() %>% check_error()
success_msg("Great thinking!")
Many functions will take in a vector as the input. For example, try using sum()
to total up the five values saved in my.vector. Note that we have already saved some values in my.vector for you.
my.vector < c(100,200,300,400,500)
#Use sum() to total up the five values in my.vector
sum(my.vector)
ex() %>% check_object("my.vector")
ex() %>% check_function("sum", not_called_msg = "don't forget to use the sum() function") %>% check_result() %>% check_equal(incorrect_msg = "did you call sum() on my.vector?")
ex() %>% check_error()
We will learn about other R objects that help us organize and visualize data as we go along in the class.
What You Can Store in an R Object
You can think of R objects like buckets that hold values. An R object can hold a single value, or it can hold a group of values (as in the case of a vector). So far, we have only put numbers into R objects. But R objects can actually hold three types of values: numbers, characters, and Boolean values.
Numerical Values
If R knows that you are using numbers, it can do lots of things with them. We have seen, for example, that R can perform arithmetic operations on numbers—addition, subtraction, multiplication, and division.
#No PEC
# Here are two ways of creating a numeric vector with the numbers 1 to 10
my.num1 < c(1,2,3,4,5,6,7,8,9,10)
my.num2 < c(1:10)
# Write code to print out both of these numeric vectors
my.num1 < c(1,2,3,4,5,6,7,8,9,10)
my.num2 < c(1:10)
my.num1
my.num2
ex() %>% check_object("my.num1") %>% check_equal()
ex() %>% check_object("my.num2") %>% check_equal()
ex() %>% check_output_expr("my.num1", times = 2, missing_msg = "Did you print out both my.num1 and my.num2?", append = FALSE)
ex() %>% check_error()
Note that in R when we use a colon like this, 1:10, it means 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. That’s pretty convenient. Imagine if you needed a vector with the numbers from 1 to 10,000! The colon would be a big time saver.
Character Values
Characters are comprised of text, such as words or sentences. (Numbers can also be treated as characters, depending on the context. For example, when 20 is in quotation marks like this – “20” – it will be treated as a character value, even though it includes a number.) Character values are in between quotation marks, " " (R doesn’t usually care whether you use single quotes, ‘like this’, or double quotes, “like that”). We’ll mostly use double quotes for consistency.
If we forget the quotes, R will think that a word is a name of an object instead of a character value.
many.hellos < c("hi", "hello", "hola", "bonjour", "ni hao", "merhaba")
many.hellos < c("hi", "hello", "hola", "bonjour", "ni hao", "merhaba")
# Write code to print out the 5th way of saying hello in this vector
many.hellos < c("hi", "hello", "hola", "bonjour", "ni hao", "merhaba")
# Write code to print out the 5th way of saying hello in this vector
many.hellos[5]
ex() %>% check_object("many.hellos") %>% check_equal(incorrect_msg = "Make sure not to change the contents of many.hellos")
ex() %>% check_output_expr("many.hellos[5]", missing_msg = "You can use [] to select the 5th element in many.hellos")
ex() %>% check_error()
success_msg("Fantastic work!")
Boolean Values
Boolean values are either TRUE or FALSE. Maybe we have a question such as: Is the first element in the vector many.hellos “hi”? We can ask R to find out and return the answer TRUE or FALSE. We can do that by using the comparison operator == (it just means equal).
many.hellos < c("hi", "hello", "hola", "bonjour", "ni hao", "merhaba")
# See what happens when you submit this code:
many.hellos[1]== "hi"
# See what happens when you submit this code:
many.hellos[1]== "hi"
ex() %>% check_output_expr("many.hellos[1]=='hi'", missing_msg = "Make sure you don't change the code before pressing Submit")
ex() %>% check_error()
If we want, we can store that answer in an R object.
many.hellos < c("hi", "hello", "hola", "bonjour", "ni hao", "merhaba")
# Write some code that will store the answer to the question, "is the first element in the vector many.hellos "hi"? in an R object called firstIsHi
# Write some code that will store the answer to the question, "is the first element in the vector many.hellos "hi"? in an R object called firstIsHi
firstIsHi < many.hellos[1] == "hi"
ex() %>% check_operator("==") %>% check_result() %>% check_equal()
ex() %>% check_object("firstIsHi") %>% check_equal()
ex() %>% check_error()
success_msg("Nice work!")
Most of the questions we ask R to answer with a TRUE or FALSE involve comparison operators such as >, <, >=, <=, and ==. The double == sign checks if two values are equal. There is even a comparison operator to check whether values are not equal: !=. For example, 5 != 3 is a TRUE statement.
#No PEC
# Read this code and predict what value will come out of the R console. Then run the code and see if you were right.
A < 1
B < 5
Compare < A > B
Compare
A < 1
B < 5
Compare < A > B
Compare
ex() %>% check_object("A") %>% check_equal(incorrect_msg = "Make sure not to change the contents of A")
ex() %>% check_object("B") %>% check_equal(incorrect_msg = "Make sure not to change the contents of B")
ex() %>% check_object("Compare") %>% check_equal(incorrect_msg = "Make sure not to change the contents of Compare")
ex() %>% check_output_expr("Compare", missing_msg = "Make sure to print Compare")
success_msg("Great work!")
Note that Compare in the code above is not a function. You know this because there is no () after it. Compare, in this case, is just a name we made up for an R object to store the Boolean result of the question, “Is A greater than B?”. The answer, as we can see, is FALSE.
We can also create Boolean vectors by subjecting a whole vector to a comparison. Let’s create a numeric vector with the numbers from 1 to 10 (we will call this vector my.numbers). Then let’s create a Boolean vector called my.booleans to store the results of checking whether each number in the my.numbers vector is greater than or equal to 5.
#no PEC
# Here's the code to create the my.numbers vector:
my.numbers < c(1:10)
# And here's the code to check whether each element of the vector my.numbers is greater than or equal to 5, storing the result in a new vector called my.booleans.
my.booleans < my.numbers >= 5
# This code prints out both vectors
my.numbers
my.booleans
my.numbers < c(1:10)
my.booleans < my.numbers >= 5
my.numbers
my.booleans
ex() %>% check_object("my.numbers") %>% check_equal(incorrect_msg = "Make sure to keep the line that assigns c(1:10) to my.numbers")
ex() %>% check_object("my.booleans") %>% check_equal(incorrect_msg = "Make sure you assign my.numbers>= 5 to my.booleans")
ex() %>% check_output_expr("my.numbers", missing_msg = "Did you print my.numbers?")
ex() %>% check_output_expr("my.booleans", missing_msg = "Did you print my.booleans?")
ex() %>% check_error()
success_msg("Fantastic work!")
# What do you expect from this code? Run the code to see what happens. Then, fix the bug and run again.
A < 5
B < 5
Compare < A = B
Compare
# What do you expect from this code? Run the code to see what happens. Then, fix the bug and run again.
A < 5
B < 5
Compare < A == B
Compare
ex() %>% check_object("A") %>% check_equal(incorrect_msg = "Make sure the object A is assigned the value 5")
ex() %>% check_object("B") %>% check_equal(incorrect_msg = "Make sure the object B is assigned the value 5")
ex() %>% check_operator("==") %>% check_result() %>% check_equal()
ex() %>% check_object("Compare") %>% check_equal()
ex() %>% check_output_expr("Compare", missing_msg = "Did you tell R to print Compare?")
ex() %>% check_error()
success_msg("Nice thinking!")
In R, we will avoid using the single equal sign, =. If you want to know whether A is equal to B, use the double equal sign, ==. The single equal sign is sometimes used instead of the assignment operator, <, which can get confusing, both to you and to R. Use the arrow < to assign values to an R object, and == to ask whether two values are equal.
R for Humans
Programming languages are primarily for communicating with computers. But there are a lot of things we do when we write R to communicate with humans. For example, R doesn’t care if we write spaces between things. We will write A < 5
and we put spaces in there. But we don’t do it for R. R thinks that A<5
is the same as A < 5
. We add the spaces to make it easier for a human to read. The same goes for comments (that begin with #); R will ignore that code but it may be useful for a human reading the code.
Also, we are mindful that R is a computer language and doesn’t actually “think” or “care” or “ignore” anything, but we will commonly anthropomorphize R. Many readers of this book are new to programming and it might be helpful to think about programming as communicating with R.