list

Statistics and Data Science: A Modeling Approach

1.4 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.

# 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 can just type the name of the object myfavoritenumber # now revise the code to use your actual favorite number. # This is an example --- use your favorite number! myfavoritenumber <- 17 myfavoritenumber ex() %>% { check_object(., "myfavoritenumber") check_output_expr(., "myfavoritenumber") }
Don't forget to modify the code with your favorite number
DataCamp: ch1-9

Now remember, R is case sensitive. Try assigning 5 to num and 10 to NUM.

# Assign 5 to num and 10 to NUM num <- NUM <- # Write the name of the object that contains 10 and then press the RUN button # Doing so prints out the contents of that object num <- 5 NUM <- 10 NUM msg_undefined <- "Make sure to define both variables: num and NUM." msg_incorrect <- "Make sure you assign the correct value to each variable." msg_not_print <- "Don't forget to print out the object that contains 10." ex() %>% { check_object(., 'num', msg_undefined) %>% check_equal(msg_incorrect) check_object(., 'NUM', msg_undefined) %>% check_equal(msg_incorrect) check_output_expr(., "NUM", missing_msg = msg_not_print) }
Don't forget to print out the object that contains 10.
DataCamp: ch1-10

NOTE: When you save an R object in DataCamp (i.e., in our book) it will only be saved until you leave the page. If you re-load the page later it won’t be there.

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 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.

# 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 # or print(my.vector) my.vector2 # or print(my.vector2) ex() %>% { check_object(., 'my.vector') check_object(., 'my.vector2') check_output_expr(., "my.vector") check_output_expr(., "my.vector2") }
Make sure to type the name of each variable to print it to the R console
DataCamp: ch1-11

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 DataCamp window below.

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() check_operator(., "*") %>% check_result() %>% check_equal() }
Use the asterisk symbol [*] to multiply
DataCamp: ch1-12

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.

# 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") check_operator(., "*") %>% check_result() %>% check_equal(incorrect_msg = "Make sure to keep the line my.vector * 100") check_output_expr(., "my.vector", missing_msg = "Did you print my.vector?") }
Simply click the Run button and observe the output
DataCamp: ch1-13

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) # This creates `my.vector` and stores 1, 2, 3, 4, 5 in it my.vector <- c(1,2,3,4,5) # Now write code to save `my.vector * 100` back into `my.vector` my.vector <- my.vector <- c(1,2,3,4,5) my.vector <- my.vector * 100 ex() %>% { check_operator(., "*") %>% check_result() %>% check_equal() check_object(., "my.vector") %>% check_equal() }
DataCamp: ch1-14

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 # Write code to get the 4th value 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`?")
Use `[ ]` to index
DataCamp: ch1-15

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 values in my.vector sum(my.vector) ex() %>% { check_object(., "my.vector") 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?") }
Use sum and my.vector
DataCamp: ch1-16

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.

# 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 <- 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 <- 1:10 my.num1 my.num2 ex() %>% { check_object(., "my.num1") %>% check_equal() check_object(., "my.num2") %>% check_equal() check_output_expr(., "my.num1", times = 2, missing_msg = "Did you print out both my.num1 and my.num2?", append = FALSE) }
DataCamp: ch1-17

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") # Write code to print out the 5th way of saying hello in this vector many.hellos <- c("hi", "hello", "hola", "bonjour", "ni hao", "merhaba") many.hellos[5] ex() %>% { check_object(., "many.hellos") %>% check_equal(incorrect_msg = "Make sure not to change the contents of many.hellos") check_output_expr(., "many.hellos[5]", missing_msg = "You can use [] to select the 5th element in many.hellos") }
Remember to use [] to index an element in a vector
DataCamp: ch1-18

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" 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")
Did you press Submit?
DataCamp: ch1-19

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 firstIsHi <- many.hellos[1] == "hi" ex() %>% { check_operator(., "==") %>% check_result() %>% check_equal() check_object(., "firstIsHi") %>% check_equal() }
Use the [] to select the first element and use == to answer whether or not the element is equal to "hi"
DataCamp: ch1-20

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.

# 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") check_object(., "B") %>% check_equal(incorrect_msg = "Make sure not to change the contents of B") check_object(., "Compare") %>% check_equal(incorrect_msg = "Make sure not to change the contents of Compare") check_output_expr(., "Compare", missing_msg = "Make sure to print Compare") }
Just click Submit
DataCamp: ch1-21

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.

# 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") check_object(., "my.booleans") %>% check_equal(incorrect_msg = "Make sure you assign my.numbers>= 5 to my.booleans") check_output_expr(., "my.numbers", missing_msg = "Did you print my.numbers?") check_output_expr(., "my.booleans", missing_msg = "Did you print my.booleans?") }
Just click Submit
DataCamp: ch1-22

# 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 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") check_object(., "B") %>% check_equal(incorrect_msg = "Make sure the object B is assigned the value 5") check_operator(., "==") %>% check_result() %>% check_equal() check_object(., "Compare") %>% check_equal() check_output_expr(., "Compare", missing_msg = "Did you tell R to print Compare?") }
Use == to test if two values are equal
DataCamp: ch1-23

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 course are new to programming and it might be helpful to think about programming as communicating with R.