Creating Variables
The assignment arrow binds a name to a value, and names are case-sensitive, start with a letter or a dot, and may contain letters, digits, dots and underscores.
Assign names to values and inspect which objects an expression uses.
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.