Creating Variables
The garden's total this week is 45 kg across 5 plots. You could type 45 / 5 every time you need the average, but the moment next week's numbers arrive you would have to hunt down every 45. Variables let you name a value once and use the name everywhere.
The rule
Name on the left, arrow pointing at it:
name <- value.
The arrow <- takes the value on its right and stores it under the name on its left. Read it aloud as "gets": total_kg gets 45.
total_kg <- 45
plot_count <- 5
avg_kg <- total_kg / plot_count # 9
avg_kg # [1] 9
Avg_kg # Error: object 'Avg_kg' not foundAssignment prints nothing. To assign and see the result in one go, wrap the line in brackets: (avg_kg <- total_kg / plot_count) prints [1] 9. Typing <- is quick in RStudio and Positron: Alt + minus (Option + minus on a Mac) inserts it with spaces.
= also assigns at the top level, but R style guides use <- for assignment and keep = for naming arguments inside a function call, as in round(avg_kg, digits = 1). Sticking to that split keeps code easy to read.
Naming rules:
- Letters, digits,
.and_only. - Start with a letter, or a dot that is not followed by a digit.
plot_2andharvest.totalare fine;2nd_plotand_plotare not. - Case matters:
avg_kgandAvg_kgare different names. - Reserved words such as
if,else,for,function,TRUEandNULLcannot be names. - A hyphen is never part of a name:
plot-countmeans plot minus count.
The tidyverse style guide recommends lower-case snake_case: short, descriptive nouns such as total_kg.
Assigning to an existing name replaces its value. ls() lists the names you have created, and rm(avg_kg) removes one.
One more rule that surprises newcomers: assignment makes an independent copy. After backup <- kg, changing kg later leaves backup untouched.
The shortcut
Evaluate right side first, then attach the name. R never looks at the left side until the right side has become a value.
Look up total_kg
R finds the stored value: 45.
This is why x <- x + 2 is fine: the old x is read on the right before the new value is stored on the left.
Drills
Answer fast — trust the rule.
Which of these is a valid R variable name?
After x <- 5 and then x <- x + 2, what is x?
In a fresh session you run Total <- 45, then type total. What happens?
With kg <- c(12.5, 8, 15, 3.5, 6), you run backup <- kg, then kg[1] <- 0. What is backup[1]?
What does (avg_kg <- 45 / 5) do?
Remember
- Name on the left, arrow pointing at it:
name <- value. - Shortcut: evaluate the right side first, then attach the name.
- Trap: names are case-sensitive, cannot start with a digit or underscore, and never contain a hyphen.
