Section1.4Creating 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?
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.
# 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).