๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Variables

A variable is a name that holds a value. The name lets a script use the same value again later.

Store text in a name

The first line stores text in a name. The second line prints the stored text.

name <- "Ana"
print(name)

Store a number in a name

The first line stores a number in a name. The second line prints the stored number.

score <- 88
print(score)

A new value replaces the old one

The name first holds the number 1. A new value then replaces it with 2.

level <- 1
print(level)
level <- 2
print(level)

A wrong name fails

The stored name and the printed name differ by one letter. R stops with an error for the unknown name.

total <- 5
print(totl)

Example

player.name <- "Mia"
player.score <- 76
print(player.name)
print(player.score)

Key points

  • The <- symbol stores a value in a name.
  • Read the <- symbol as the word gets.
  • Names start with a letter.
  • Names may also hold digits, dots, and underscores after the first letter.
  • Storing a new value in a name replaces the old value.
  • An assignment on its own line prints nothing.
  • Using a name that was never stored stops the script with an error.

In this example two names store a text value and a number value. Both names use a dot, which R allows inside a name. The print lines show the stored values.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What happens when a name gets a new value?