Objects in R

If we want to save a value, we create an object.

my_num1 <- 4        # <- is called the assignment operator
                    # my_num1 is the name of the object in which the value is stored

In this code chunk, we used the assignment operator (<-) to store 4 in the object (my_num1).

To see what is stored in the object my_num1, we can ask R to return its value:

my_num1
## [1] 4

And we can be more explicit by using the print function:

print(my_num1)
## [1] 4

We can use my_num1 in other operations and function calls.

Add 3 to my_num1:

my_num1 + 3
## [1] 7

Find the log of my_num1:

log(my_num1)
## [1] 1.386294

Take the square root of my_num1:

sqrt(my_num1)
## [1] 2

Go back to line 16, assign a different value to my_num1, and run through the code chunks again.

This is a great benefit of creating objects: We can easily run through many code chunks just by making a single change.

Object names

There are some restrictions to how you can name objects. Your objects cannot start with numbers or special characters including +, -, *, /, ^, !, @, and &.

Here are some examples of object names that you can use:

my_num1

count

abs_num

x

Here are some examples of object names that you cannot use:

!num

2times2

*char

&fun

Examples

We can store the output from a function in an object:

my_num <- -4

abs_num <- abs(my_num)

print(abs_num)
## [1] 4

Can you think of why creating two objects here (my_num and abs_num) could be useful?

Write a code chunk to store the value 3 to the object x, add 7 to it, and print the sum.

x <- 3
x + 7
## [1] 10

Practice

1.) Write a code chunk to store the value 7.8 to a new object and print the value of your object.

2.) Write a code chunk to store the absolute value of -3 to the object y and print the value stored in y.

3.) Are the following names acceptable as R object names?

game

&twist

^number

divide

ten

*math

Test each by trying to assign the value 12 to the names:

Super! Congratulations!

You assigned code to R objects! This is critical to everything else we will do this summer!

You are gaining a solid foundation in R fundamentals!