R Variables

A variable is a named storage location in your computer's memory. You give data a name, and R remembers that data under that name for as long as your session runs. Variables are the foundation of every R program — without them, you cannot store or reuse information.

The Variable Concept: A Real-World Analogy

  Variable  =  Labeled Box
  ─────────────────────────────────────────
  Name      →  Label on the box
  Value     →  Contents inside the box
  Memory    →  The shelf where boxes sit
  ─────────────────────────────────────────

  Example:
  ┌─────────────┐    ┌────────────────┐
  │  city       │    │   "Mumbai"     │
  │  (label)    │ ──►│   (contents)   │
  └─────────────┘    └────────────────┘

Creating a Variable in R

R uses the <- operator (a left-pointing arrow) to assign a value to a variable. This is the most common and recommended style in R.

age <- 28
name <- "Anjali"
price <- 499.95
is_active <- TRUE

You can also use the equals sign = for assignment, though <- is preferred in R community style:

score = 87   # works, but <- is preferred

Check the values by printing them:

print(age)
print(name)

Output:

[1] 28
[1] "Anjali"

Variable Naming Rules

R enforces specific rules for naming variables:

  • Names can contain letters, numbers, dots (.), and underscores (_)
  • Names must start with a letter or a dot
  • Names cannot start with a number
  • R is case-sensitive: Age and age are two different variables
  • You cannot use reserved words like if, else, TRUE, FALSE as variable names
Valid Names             Invalid Names
────────────────────    ─────────────────────
total_sales             1total       (starts with number)
product.name            my-variable  (hyphen not allowed)
scoreV2                 TRUE         (reserved keyword)
.hidden_var             @score       (@ not allowed)

Variable Naming Styles

Several naming styles exist in R. Pick one and use it consistently throughout your project.

Style               Example
──────────────────  ───────────────────────
snake_case          total_sales_2024
camelCase           totalSales2024
dot.case            total.sales.2024

Snake case (total_sales_2024) is the most widely used style in modern R code.

Updating a Variable

You can change a variable's value at any time by assigning a new value to the same name.

temperature <- 20
print(temperature)   # outputs 20

temperature <- 35    # overwrite with new value
print(temperature)   # outputs 35

The old value (20) is gone. The variable now holds 35. R always stores the most recent assignment.

Using Variables in Calculations

# Calculating total cost of items in a cart
item_price <- 250
quantity <- 4
discount <- 50

total <- (item_price * quantity) - discount
print(total)

Output:

[1] 950

Each variable stores one piece of information. The formula combines them into a meaningful result.

Multiple Assignment

R lets you assign the same value to multiple variables in one line using the right-facing arrow:

a <- b <- c <- 100
print(a)   # 100
print(b)   # 100
print(c)   # 100

Checking Variable Type

Use class() to find out what type of data a variable holds.

age <- 30
name <- "Rohan"
flag <- TRUE

class(age)    # "numeric"
class(name)   # "character"
class(flag)   # "logical"

Viewing All Variables

The ls() function lists all variables currently in memory.

ls()

Output (example):

[1] "age"   "flag"  "name"  "total"

This matches what you see in the Environment tab of RStudio.

Removing a Variable

Use rm() to delete a variable from memory when you no longer need it.

rm(age)          # removes the 'age' variable
rm(list = ls())  # removes ALL variables — use carefully!

Variable Scope Overview

Global Scope              Local Scope
────────────────────────  ─────────────────────────────
Variables created in      Variables created inside a
the main script           function (disappear after
                          function finishes)
Available everywhere      Only available inside that
in your session           function

You will learn more about scope when studying functions. For now, all variables you create at the top level of your script are global and available throughout your session.

Variables make your programs flexible and reusable. Instead of hardcoding numbers in multiple places, store them in variables. When a value changes, you update it in one place and the rest of the code adjusts automatically.

Leave a Comment

Your email address will not be published. Required fields are marked *