Data structures organize and store data in R for easy access and manipulation. Understanding data structures is essential for effective programming and data analysis in R.
The simplest data structure in R. A vector is a sequence of elements of the same type (numeric, character, logical, etc.).
# Numeric vector num_vec <- c(1, 2, 3, 4, 5) # Character vector char_vec <- c("apple", "banana", "cherry") # Logical vector log_vec <- c(TRUE, FALSE, TRUE)
Lists are collections of elements that can be of different types (numbers, strings, vectors, even other lists).
my_list <- list( name = "Alice", age = 25, scores = c(85, 90, 88), married = FALSE )
You can access list elements by name or position:
my_list$name # "Alice" my_list[[3]] # c(85, 90, 88)
Matrices are 2-dimensional arrays with elements of the same type, arranged in rows and columns.
mat <- matrix(1:6, nrow=2, ncol=3) print(mat) # Output: # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6
Arrays can have more than two dimensions. They store data of the same type.
arr <- array(1:12, dim = c(2, 3, 2)) print(arr)
Data frames are 2-dimensional tabular data structures like spreadsheets or SQL tables. Columns can be different types.
df <- data.frame( id = 1:3, name = c("John", "Jane", "Tom"), age = c(28, 25, 31), married = c(TRUE, FALSE, TRUE) ) print(df)
Factors represent categorical data with fixed possible values called levels.
colors <- factor(c("red", "blue", "red", "green")) print(colors) levels(colors) # Shows possible categories: "blue", "green", "red"
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!