Variables and Data Types in R
In R, variables are used to store data values. R is dynamically typed, meaning you don't need to declare the type of a variable explicitly. Variables can hold different types of data, such as numbers, strings, logical values, vectors, and more.
Declaring Variables
Variables in R are created when you assign a value to them using the assignment operator <-
or =
.
x <- 10 # Numeric
name <- "Alice" # Character
is_student <- TRUE # Logical
Common Data Types
- Numeric: Represents decimal numbers (e.g.,
10
,3.14
). - Character: Represents text data (e.g.,
"Hello"
,'R'
). - Logical: Represents true or false values (
TRUE
,FALSE
). - Vector: Ordered collection of elements of the same type (e.g.,
c(1, 2, 3)
). - Data Frame: Tabular data structure with rows and columns (e.g.,
data.frame()
). - Factor: Represents categorical data (e.g.,
factor(c("A", "B", "C"))
).
Example:
age <- 25
name <- "Alice"
is_student <- TRUE
scores <- c(90, 85, 95)
print(paste("Name:", name))
print(paste("Age:", age))
print(paste("Is Student:", is_student))
Type Conversion
You can convert one data type to another using functions like as.numeric()
, as.character()
,
and as.logical()
.
x <- "10"
x_numeric <- as.numeric(x) # Convert character to numeric
x_character <- as.character(x_numeric) # Convert numeric to character
x_logical <- as.logical(x_numeric) # Convert numeric to logical
print(x_numeric) # Output: 10
print(x_character) # Output: "10"
print(x_logical) # Output: TRUE
Vectors
Vectors are the most basic data structure in R. They can hold elements of the same type.
numbers <- c(1, 2, 3, 4, 5) # Numeric vector
names <- c("Alice", "Bob", "Charlie") # Character vector
flags <- c(TRUE, FALSE, TRUE) # Logical vector
print(numbers)
print(names)
print(flags)
Data Frames
Data frames are used to store tabular data. They are similar to tables in a database or Excel sheets.
data <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
is_student = c(TRUE, FALSE, TRUE)
)
print(data)
Factors
Factors are used to represent categorical data. They can be ordered or unordered.
categories <- factor(c("Low", "Medium", "High"), levels = c("Low", "Medium", "High"), ordered = TRUE)
print(categories)
Checking Data Types
You can check the data type of a variable using functions like class()
, typeof()
, and is.numeric()
.
x <- 10
print(class(x)) # Output: "numeric"
print(typeof(x)) # Output: "double"
print(is.numeric(x)) # Output: TRUE
Special Values
R has special values like NA
(missing value), NULL
(empty object), and Inf
(infinity).
x <- NA # Missing value
y <- NULL # Empty object
z <- Inf # Infinity
print(x) # Output: NA
print(y) # Output: NULL
print(z) # Output: Inf
Next: Control Structures