2.2 Assignment operator
For instance, instead of adding 3 + 5, we can assign those values to objects and then add them.
# assign 3 to a
a <- 3
# assign 5 to b
b <- 5
# what now is a
a
# what now is b
b
# Add a and b
a + b
<-
is the assignment operator. It assigns values on the right to objects on the left. So, after executing x <- 3
, the value of x
is 3
. The arrow can be read as 3 goes into x
. You can also use =
for assignments but not in all contexts so it is good practice to use <-
for assignments. =
should only be used to specify the values of arguments in functions, see below.
In RStudio, typing Alt + -
(push Alt
, the key next to your space bar at the same time as the -
key) will write <-
in a single keystroke.
To view which objects we have stored in memory, we can use the ls()
command
ls()
To remove objects we can use the rm()
command
rm(a)
2.2.1 Exercise
- What happens if we change
a
and then re-adda
andb
? - Does it work if you just change
a
in the script and then adda
andb
? Did you still get the same answer after they changeda
? If so, why do you think that might be? - We can also assign a + b to a new variable,
c
. How would you do this?