Variables in R

basics
r-programming
Learn how to create and work with variables in R
Published

March 30, 2025

Creating Variables in R

Variables in R are used to store data that can be referenced and manipulated throughout your code. Here’s how to create and work with variables:

Basic Assignment

# Using the assignment operator (<-)
x <- 10
y <- "Hello, R!"
z <- TRUE

# Print the variables
x
[1] 10
y
[1] "Hello, R!"
z
[1] TRUE

Alternative Assignment Methods

# Using the equals sign (=)
age = 25

# Using the assignment operator in reverse (->)
"Data Scientist" -> job_title

# Print the variables
age
[1] 25
job_title
[1] "Data Scientist"

Variable Naming Rules

  • Names can contain letters, numbers, dots (.) and underscores (_)
  • Names must start with a letter or a dot
  • If a name starts with a dot, it cannot be followed by a number
  • Names are case-sensitive (Value and value are different variables)
# Valid variable names
valid_name <- 1
validName <- 2
valid.name <- 3
.hidden <- 4

# Print variables
valid_name
[1] 1
validName
[1] 2
valid.name
[1] 3
.hidden
[1] 4

Data Types

R has several basic data types:

# Numeric
num <- 42.5
typeof(num)
[1] "double"
# Integer (note the L suffix)
int <- 42L
typeof(int)
[1] "integer"
# Character
text <- "R programming"
typeof(text)
[1] "character"
# Logical
flag <- TRUE
typeof(flag)
[1] "logical"

Checking and Converting Types

# Check if a variable is of a specific type
is.numeric(num)
[1] TRUE
is.character(text)
[1] TRUE
# Convert between types
as.character(num)
[1] "42.5"
as.numeric("100")
[1] 100
as.logical(1)
[1] TRUE

Variable Information

# Get information about a variable
x <- c(1, 2, 3, 4, 5)
class(x)
[1] "numeric"
length(x)
[1] 5
str(x)
 num [1:5] 1 2 3 4 5

Remember that R is dynamically typed, so variables can change types during execution. This flexibility is one of R’s strengths for data analysis.