Unit 02.01: Assignment, and the space that changes its meaning
R has three ways to assign a value, and one of them is a typo away from a comparison.
Use <-, and mind the space
x <- 5 is the form to write. x = 5 also works, but = does a second job in R โ it names arguments inside a function call โ so keeping it for that one purpose removes an ambiguity for the reader. 5 -> x is legal and reads backwards; you will see it occasionally and need not write it.
Assignment is silent. R stores the value and prints nothing, which is why beginners often assume nothing happened. Wrapping the whole statement in parentheses assigns *and* prints, which is handy while you are exploring.
This block uses all three forms, then shows the trap.
# `<-` assigns. It is not the only thing that looks like it does.
visits <- 412 # the form to use
ward = "North" # works, but `=` also names function arguments
502 -> east # legal, and reads backwards
cat("visits:", visits, " ward:", ward, " east:", east, "\n\n")
# The classic slip: one missing space changes the meaning completely.
x <- 5
cat("x <- 5 assigns, so x is:", x, "\n")
cat("x < -5 compares, and evaluates to:", x < -5, "\n")
# Assignment is silent; wrapping it in parentheses prints as well as assigns.
(total <- visits + east)
The three assignments give 412, North and 502 as expected. Then the important pair: x <- 5 assigns, so x is 5, while x < -5 is a comparison and evaluates to FALSE. One space is the entire difference, and R reports no error either way โ it simply does something else. The parenthesised assignment at the end prints 914, its value, while still storing it.
The mistake this prevents
The mistake is writing x<-5 with no spaces and later reading it as a comparison, or writing if (x < -5) and losing the space. Both are syntactically valid, so nothing warns you.
Takeaway
Use <- for assignment and = only for function arguments. Put spaces around every operator, which makes <- and < - visibly different.
