Labs ICT
โญ Pro Login

Variables

Variables are how R remembers things. Instead of typing the same number over and over, you store it once and use the name. It's like putting a label on a box โ€” the box holds the value, and the label is how you find it later.

Assignment with <-

The classic R assignment operator is <-. It's a left-pointing arrow made of a less-than sign and a hyphen. You put the name on the left, the arrow, and the value on the right. R reads it as "store this value under this name".


# Storing values with <-
city <- "New York"
population <- 8336817
city
population
    
Try it Yourself โ†’

= Also Works

You can use = for assignment too. It works exactly the same as <- in most cases. But the R community strongly prefers <-. Why? Tradition, mostly. = is also used inside function arguments, so using <- avoids confusion. My advice: use <- when you're storing a variable and = when you're passing arguments to a function.


# Using = for assignment (works but less common)
temperature = 72
temperature
    
Try it Yourself โ†’

Variable Naming Rules

R has a few rules for naming variables. A name must start with a letter or a dot (but a dot can't be followed by a number). After the first character, you can use letters, numbers, dots, and underscores. Case matters, so Score and score are different.


# Valid names
my_var <- 1
my.var <- 2
MyVar2 <- 3

# Invalid names (will error)
# 2var <- 10
# _var <- 20
# .2var <- 30
    
Try it Yourself โ†’

Printing Variables

There are several ways to see what a variable holds. The simplest is to just type the name and hit Enter. You can also use print() or cat() (which prints without quotes). In RStudio, you can also see all your variables in the Environment panel โ€” no typing needed.


# Different ways to print
greeting <- "Hey there!"
greeting           # Auto-print
print(greeting)    # Explicit print
cat(greeting)      # Print without quotes
    
Try it Yourself โ†’

Variables are the foundation. Once you get comfortable with storing and naming values, you're ready to explore the different types of data R can hold.

๐Ÿงช Quick Quiz

How do you print a variable in R?