Variables and Assignment
Prerequisites: R syntax basics
A variable gives a name to a value so you can use it later.
Real-world analogy: a variable is a labeled box. You write a name on the box and put something inside; later you refer to the box by its name.
Syntax
R's assignment operator is <- (a "less than" sign and a hyphen):
city <- "Lagos"
temperature <- 24
= also works for assignment, but <- is the standard R style, and
= is normally reserved for naming function arguments. RStudio types
<- for you with Alt + - (Option + - on macOS).
Example
city <- "Lagos"
temperature <- 24
city
temperature
temperature <- 27
temperature
temperature <- temperature + 1
temperature
Expected output
[1] "Lagos"
[1] 24
[1] 27
[1] 28
Assigning a new value replaces the old one. R has no += operator —
write temperature <- temperature + 1.
Naming
- Use descriptive names in
snake_case:mean_height,total_sales. - Avoid names of common functions like
mean,c,t, ordata— R allows it, but it's confusing.
Listing and removing variables
rm(list = ls())
x <- 1
y <- 2
ls()
rm(x)
ls()
[1] "x" "y"
[1] "y"
Common mistakes
- Using a variable before creating it:
Error: object 'total' not found. - Writing
x < - 5(with a space) — that comparesxwith-5instead of assigning.
Practice
Create a variable apples equal to 5, add 3 to it, and print
I have 8 apples using cat.
Show solution
apples <- 5
apples <- apples + 3
cat("I have", apples, "apples\n")
I have 8 apples