TExcelTAD
Home › R › R Variables

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.

r · try it yourself
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)
r · try it yourself
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:

r · try it yourself
(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:

r · try it yourself
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:

r · try it 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:

r · try it yourself
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?

  1. x := 5
  2. x <- 5
  3. let x = 5
  4. x == 5

Which is NOT a valid variable name?

  1. sales_2024
  2. .tmp
  3. 2nd_place
  4. firstName

What does (n <- 7) do?

  1. Only assigns
  2. Assigns 7 to n and prints 7
  3. Compares n with 7
  4. Creates a vector of 7 zeros