R Assignment Operators
Assignment Operators
Assignment operators are used to store values in variables.
You already know the most common one from the Variables chapter: <- stores the value on the right in the variable on the left:
Example
x <- 10
x
Try it Yourself »
Other Ways to Assign
R has two more ways to assign a value. = works like <-, and -> assigns from left to right:
Example
x <- 5
y = 10
15 -> z
x
y
z
Try it Yourself »
A list of the assignment operators:
| Operator | Example | Description |
|---|---|---|
| <- | x <- 5 | Stores 5 in x (the most common way in R) |
| = | x = 5 | Same as x <- 5 |
| -> | 5 -> x | Same as x <- 5, but written from left to right |
| <<- | x <<- 5 | Global assignment, used inside functions |
Tip: Most R programmers use <-. Use it in your own code too, so it is easy to read for others.
You will learn more about <<- in the Global Variables chapter.
Change the Value of a Variable
Many programming languages have shorthand operators like += to add a value to a variable. R does not have them.
Instead, use the variable on both sides of <-:
Example
score <- 10
score <- score + 5
score
Try it Yourself »
R first calculates score + 5 (which is 15), and then stores the result back in score.
Real-Life Example: Counting People
Imagine a program that counts how many people are in a room. Add 1 when someone enters, and subtract 1 when someone leaves:
Example
people <- 0
people <- people + 1
people <- people + 1
people <- people + 1
people <- people - 1
people
Try it Yourself »
Three people entered and one person left, so there are 2 people in the room.