Skip to main content

Section 1.4 Creating Variables and Assigning Objects

In the last piece of code, we did a great job of using R as a calculator. While we were able to calculate the square root of 25, what if we need to save it this way we can call it later? What if we don’t want to have to continually run the code sqrt(25) in order to get the output?
In R, we are able to create variables and assign values to objects. In R, instead of using the = sign, we use <- to create objects.
Note: Once each piece of code is run and the objects are created, we should be able to see them in the β€œValues” part of our environment pane. It will show the name of the value as well as what it is equal to.

Within R, we can always follow this formula:.

value name <- whatever you want inside the value
Now, a few tips:
Below is some code to demonstrate.

Color and Numbers:.

Notice how all of the numbers change color in your code.
# Assigning to objects (variables)
sqrt(25) # the answer is 5

x <- 5 # Making x equal to 5

# Or, we can save the code we wrote and not the answer
x <- sqrt(25)

# Updating x
x <- x + 1
x # It is now equal to 6 and not 5

# Objects are case sensitive
X <- 7

# You can override code and change a variables value
X <- 5

# Good names: use letters, numbers, underscores; start with a letter
best_number <- 42

# Inspecting objects
class(x) # x is numeric, as we already knew!
[1] 5
[1] 6
[1] "numeric"

Creating vs calling:.

Notice that creating and calling the data are different. I create x <- 5, but in order to call it, I just run x (after it has been created).
With an object, there is only one value. One thing equals one thing. To build upon objects, we can move to vectors.