R Variables

Variables in R are named containers that store data values so you can reuse, update, and reference them throughout your code.

Creating Variables

A variable is created the moment you assign a value to a name using <-. R does not require you to declare a variable's type in advance — the type is determined automatically from the value you assign.

Example

name <- "Ava"
age <- 29
is_member <- TRUE
print(name)
print(age)
print(is_member)

Variables Can Change

Reassigning a variable simply replaces its previous value with a new one. R does not keep any history of the old value once it has been overwritten.

Example

score <- 70
print(score)
score <- 95
print(score)

Checking a Variable's Type

Every variable has an underlying data type, such as numeric, character (text), or logical (TRUE/FALSE). The class() function reports a variable's type, which is useful when debugging unexpected behavior.

Valueclass() Result
42numeric
"hello"character
TRUElogical
42Linteger

Variables Are Case-Sensitive

Score and score would be treated as two entirely different variables in R, so consistent capitalization matters whenever you refer back to a variable you created earlier.

Note: Use print(x) to display a variable inside a script or function; typing just x by itself only auto-prints when run directly in the console, not inside a sourced script or a function body.

Exercise: R Variables

Which assignment operator is the traditionally preferred style in R?