</>
Skip to content
R lessons (5/41)

R — Variables

Creating variables

Use the assignment operator <- to create variables:

name <- "Ada"
age <- 36
is_active <- TRUE
score <- 95.5

R figures out the type automatically — no type declarations needed.

Assignment operators

R has three assignment operators:

x <- 5       # preferred: reads left to right
x = 5        # works, but not R convention
x -> 5       # works, but rare and confusing

The community standard is <-. Use it consistently.

Variable names

R variable names must follow these rules:

# Valid names
student_name <- "Ada"
student.count <- 36
.student <- "hidden"
_first <- "starts with dot"

# Invalid names
# 2nd_place <- "no starting digit"
# my-name <- "dash means minus"
# function <- "reserved word"

Convention: use snake_case for variables and functions:

# Good
student_count <- 50
get_average <- function(x) mean(x)

# Bad
studentCount <- 50  # camelCase — not R style
Student_Count <- 50 # PascalCase — not R style

Checking types and values

x <- 42

class(x)      # "numeric"
typeof(x)     # "double"
is.numeric(x) # TRUE
is.character(x) # FALSE

# Inspect any object
str(x)
  • class() — the high-level class
  • typeof() — the underlying storage type
  • is.*() — type checking functions

Special values

# Missing value
x <- NA
is.na(x)     # TRUE

# Not a number
x <- 0/0
is.nan(x)    # TRUE

# Infinity
x <- 1/0
is.infinite(x) # TRUE

# NULL — nothing
x <- NULL
is.null(x)   # TRUE

NA vs NULL

# NA — a known missing value (a placeholder)
vec <- c(1, 2, NA, 4)
mean(vec)  # NA — result is unknown

# NULL — absence of an object entirely
vec <- c(1, 2, NULL, 4)
vec  # 1 2 4 — NULL disappears

The ls() and rm() functions

# List all variables in the environment
ls()

# Remove a specific variable
rm(x)

# Remove multiple
rm(name, age)

# Remove everything
rm(list = ls())

Variable scope

x <- "global"

my_function <- function() {
  x <- "local"
  print(x)
}

my_function()  # "local"
print(x)       # "global" — unchanged

R uses lexical scoping — functions look up variables in the environment where they were defined, not where they're called.

Assignment in functions

double_it <- function(x) {
  x <- x * 2  # modifies local copy, not the original
  return(x)
}

y <- 5
double_it(y)  # 10
print(y)      # 5 — unchanged

R passes arguments by value — functions work on copies, not originals.

Environment basics

# Create variables in the global environment
a <- 1
b <- 2

# Inspect the environment
ls()
environment()

# Create a new environment
my_env <- new.env()
my_env$x <- 10
my_env$y <- 20

Type coercion

R can convert between types automatically:

# Implicit coercion
c(1, "two", 3)     # "1" "two" "3" — all become character
c(TRUE, 1, 2)      # 1 1 2 — logical becomes numeric
c(TRUE, FALSE, 1)  # 1 0 1

# Explicit conversion
as.numeric("42")    # 42
as.character(42)    # "42"
as.logical(0)       # FALSE
as.logical(1)       # TRUE

When mixing types, R follows a hierarchy: logical → numeric → character. The most general type wins.

Factors — categorical variables

# Create a factor
colors <- factor(c("red", "blue", "green", "red", "blue"))
print(colors)
# red blue green red blue
# Levels: blue green red

# Check levels
levels(colors)  # "blue" "green" "red"

# Table of counts
table(colors)
# colors
#  blue green   red
#     2     1     2

Factors are essential for statistical modeling. They represent categorical data with a fixed set of possible values.

Constants

R doesn't have a const keyword. Use UPPER_SNAKE_CASE by convention:

PI <- 3.14159265358979
MAX_USERS <- 1000
TAX_RATE <- 0.08

The convention signals "this shouldn't change" to other developers.

Removing variables

x <- 5
y <- 10

rm(x)        # remove x
rm(y)        # remove y
rm(list = ls())  # remove everything — use with caution

Mini Practice

  1. Create variables for a book (title, author, pages, rating) and print them
  2. Check the type of each variable with class() and is.numeric()
  3. Create a factor variable representing days of the week
  4. Use ls() to list all variables, then rm() to clean up
  5. Create a vector mixing numbers and text — observe what happens

Next: the data types R provides →

Related Topics

Frequently Asked Questions about Variables

What is Variables in R?

Variables is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.

Why is Variables important in R?

Variables is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.