Skip to content

R - Variables

A variable provides us with named storage that our programs can manipulate. In R, a variable can store a wide range of objects, from a single value (like a number) to a complex structure (like a data frame or model). A valid variable name consists of letters, numbers, the dot (.), and the underscore (_) characters. It must start with a letter or a dot, but if it starts with a dot, it cannot be immediately followed by a number.

Variable NameValidityReason & Best Practice
user_idValidRecommended Style. Uses snake_case, which is preferred by the Tidyverse style guide.
var.nameValidTechnically valid, but not recommended. The . is used for S3 object-oriented programming in R and can cause confusion.
var_name%InvalidContains a special character (%). Only letters, numbers, . and _ are allowed.
2_var_nameInvalidCannot start with a number.
.internal_dataValidCan start with a dot. Such variables are ‘hidden’ by default from the ls() command.
.2_var_nameInvalidA dot at the start cannot be followed by a number.

The primary assignment operator in R is <-. While = can also be used for assignment in most cases, <- is the strong convention and is recommended to improve code clarity and avoid ambiguity with setting arguments in function calls. The rightward operator -> also exists but is rarely used.

# Best practice: Use the leftward arrow `<-` for assignment.
var_1 <- c(0, 1, 2, 3)
# The equals sign `=` also works but is best reserved for function arguments.
var_2 = c("learn", "R")
# The rightward arrow `->` is valid but unconventional.
c(TRUE, 1) -> var_3
# Use the `print()` function for explicit output.
print(var_1)
# The `cat()` function concatenates and prints, with `\n` for a new line.
cat("Variable 1 is:", var_1, "\n")
cat("Variable 2 is:", var_2, "\n")
cat("Variable 3 is:", var_3, "\n")

When we execute the above code, it produces the following result:

[1] 0 1 2 3
Variable 1 is: 0 1 2 3
Variable 2 is: learn R
Variable 3 is: 1 1

Note on Type Coercion: The vector c(TRUE, 1) contains both a logical and a numeric value. R coerces the values to the most flexible type, which in this case is numeric. Therefore, TRUE is converted to 1.

R is a dynamically typed language. This means you don’t declare a variable’s data type in advance. A variable automatically takes on the data type of the object assigned to it, and you can change this type by reassigning a different object to it.

# Assign a character string
my_variable <- "Hello, R!"
cat("The class of my_variable is:", class(my_variable), "\n")
# Reassign a numeric (double precision) value
my_variable <- 34.5
cat("Now the class of my_variable is:", class(my_variable), "\n")
# Reassign an integer value (the 'L' suffix denotes integer)
my_variable <- 27L
cat("Finally, the class becomes:", class(my_variable), "\n")

When we execute the above code, it produces the following result:

The class of my_variable is: character
Now the class of my_variable is: numeric
Finally, the class becomes: integer

You can manage the variables in your current R session (the global environment) using a few key functions.

The ls() function lists all visible variables. You can use the pattern argument to search for names, or all.names = TRUE to show hidden variables (those starting with a dot).

# Create some variables for demonstration
var_a <- 1
var_b <- "text"
.hidden_var <- TRUE
# List all visible variables
print(ls())
# List variables matching a pattern (e.g., starting with 'var')
print(ls(pattern = "^var"))
# List all variables, including hidden ones
print(ls(all.names = TRUE))

Use the rm() function to remove one or more variables from the environment. To clear your entire workspace, you can combine rm() and ls().

# Create a variable to delete
delete_me <- "I am temporary"
print(exists("delete_me"))
# Remove the variable
rm(delete_me)
print(exists("delete_me"))
# To remove all variables from the environment:
# This is a powerful command, use with care!
rm(list = ls())
print(ls())

Best Practice: For a completely clean slate, it’s often better to restart your R session (In RStudio: Session > Restart R or Ctrl+Shift+F10). This ensures that loaded packages and other environment settings are also reset.