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
Alternative Assignment Methods
# Using the equals sign (=)
age = 25
# Using the assignment operator in reverse (->)
"Data Scientist" -> job_title
# Print the variables
age
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
Data Types
R has several basic data types:
# Numeric
num <- 42.5
typeof(num)
# Integer (note the L suffix)
int <- 42L
typeof(int)
# Character
text <- "R programming"
typeof(text)
# Logical
flag <- TRUE
typeof(flag)
Checking and Converting Types
# Check if a variable is of a specific type
is.numeric(num)
# Convert between types
as.character(num)