R Variables
A variable is a name that refers to a value. You create one by assigning to it; there is no separate declaration and no type to specify.
course <- "R basics"
lessons <- 50
price <- 0
course
lessons[1] "R basics"
[1] 50
Assignment operators
R has several ways to assign, and you'll see all of them in the wild:
| Operator | Example | Notes |
|---|---|---|
<- |
x <- 5 |
the conventional choice |
= |
x = 5 |
works at top level; mostly used for function arguments |
-> |
5 -> x |
right assignment, rare |
<<- |
x <<- 5 |
assigns in an enclosing environment (see the Environments lesson) |
a <- 1
b = 2
3 -> c_value
c(a, b, c_value)[1] 1 2 3
Tip: Stick to
<-for assignment and=for naming arguments, e.g.round(x, digits = 2). RStudio inserts<-with Alt + -.
Printing while assigning
Wrapping an assignment in parentheses makes its value visible:
(area <- 4 * 2.5)[1] 10
Multiple assignment and reassignment
Variables can be reassigned at any time, even to a value of a different type. You can also chain assignments:
x <- y <- 0
x
y
x <- "now a string"
class(x)
y <- y + 1
y[1] 0
[1] 0
[1] "character"
[1] 1
Naming rules
A valid variable name:
- consists of letters, digits,
.and_; - starts with a letter, or with a
.that is not followed by a digit; - is not a reserved word such as
if,else,for,function,TRUE,NULL,NA,Inf.
| Valid | Invalid | Why invalid |
|---|---|---|
total |
2total |
starts with a digit |
total_2 |
_total |
starts with _ |
my.var |
.2x |
. followed by a digit |
myVar |
my-var |
- is the minus operator |
.hidden |
if |
reserved word |
Names that would otherwise be invalid can be used if you wrap them in backticks, which is handy for column names with spaces, but avoid creating them yourself:
`my var` <- 42
`my var` + 1[1] 43
Listing and removing variables
ls() lists the variables you have created; rm() deletes one; exists() checks for a name:
width <- 3
height <- 4
ls()
rm(width)
exists("width")
exists("height")[1] "height" "width"
[1] FALSE
[1] TRUE
Test yourself
Which of these is the conventional assignment in R?
- x := 5
- x <- 5
- let x = 5
- x == 5
Which is NOT a valid variable name?
- sales_2024
- .tmp
- 2nd_place
- firstName
What does (n <- 7) do?
- Only assigns
- Assigns 7 to n and prints 7
- Compares n with 7
- Creates a vector of 7 zeros