Skip to the workspace
Pebellslearn by building
Basic Syntax  ›  Lesson

Creating Variables

Creating Variables 10 minThe 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.

r programming / Creating Variables

Explore each scene at your own pace.

01 · The rule

The rule

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 found

Assignment 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_2 and harvest.total are fine; 2nd_plot and _plot are not.
  • Case matters: avg_kg and Avg_kg are different names.
  • Reserved words such as if, else, for, function, TRUE and NULL cannot be names.
  • A hyphen is never part of a name: plot-count means 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.