
Image by Editor | Midjourney
R is great for data analysis and statistics. Using the right data structure can make your code run faster. This improvement in performance is largely due to better memory efficiency and faster computational speed. R has many built-in structures like vectors, lists, matrices, and data frames. Each one works best for different tasks. Data structures help store and process data quickly.
This article aims to explain the main data structures in R and how to use them.
Vectors
Vectors store homogeneous elements of the same type. They can be numeric, character, or logical. Vectors support element-wise operations. Vectors form the foundation for more complex structures like matrices and arrays. Use c() to create vectors. Use square brackets [] for indexing.
# Creating a numeric vector vec <- c(1, 2, 3, 4, 5) print(vec) # Accessing elements vec[2] # Returns the second element
Output:
[1] 1 2 3 4 5 [1] 2
Lists
Lists are versatile data structures. They are useful for handling structured data, such as the output of statistical models or nested datasets. Elements can include vectors, matrices, or other lists. Lists retain each element’s structure. Use list() to create lists. Use [[ ]] or $ to access elements.
# Creating a list with different data types my_list <- list(name = "Alice", age = 25, scores = c(90, 85, 88)) print(my_list) # Accessing elements my_list$name my_list[[2]]
Output:
$name [1] "Alice" $age [1] 25 $scores [1] 90 85 88 [1] "Alice" [1] 25
Arrays
Arrays are multi-dimensional in R. They extend vectors and store homogeneous elements. Arrays can have two or more dimensions. Use array() to create them. Define dimensions when creating an array. Arrays are great for handling multi-dimensional numerical data. Indexing uses square brackets with multiple indices.
# Creating a 3D array arr <- array(1:12, dim = c(2, 3, 2)) print(arr) # Accessing elements arr[1, 2, 1] # Accesses element at row 1, column 2, and first matrix
Output:
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
[1] 3
Matrices
Matrices are two-dimensional arrays. All elements must be of the same type. They are used in math and statistics. Matrices support addition, multiplication, and transposition. Use matrix() to create them. Indexing is done with row and column positions.
# Creating a matrix mat <- matrix(1:9, nrow = 3, ncol = 3) print(mat) # Accessing elements mat[2, 3] # Returns the element at row 2, column 3 # Matrix multiplication mat %*% t(mat) # Multiplies matrix by its transpose
Output:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[1] 8
[,1] [,2] [,3]
[1,] 66 78 90
[2,] 78 93 108
[3,] 90 108 126
Data Frames
Data frames are tabular data structures. Each column can have different data types. They are useful for data analysis and manipulation. Use data.frame() to create them. Indexing is done by row and column.
# Creating a data frame
df <- data.frame(Name = c("Alice", "Bob"), Age = c(25, 30), Score = c(90, 85))
print(df)
# Accessing elements
df$Name # Returns the "Name" column
df[1, 2] # Accesses the first row, second column
Output:
Name Age Score 1 Alice 25 90 2 Bob 30 85 [1] "Alice" "Bob" [1] 25
Tibbles
Tibbles are improved data frames. They come from the tidyverse package. They offer better performance and usability. Use tibble::tibble() to create tibbles. Tibbles are useful when working with dplyr, a package for data manipulation. Tibbles are often preferred in modern data analysis workflows.
library(tibble)
# Creating a tibble
tb <- tibble(Name = c("Alice", "Bob"), Age = c(25, 30), Score = c(90, 85))
print(tb)
# Accessing elements
tb$Age
Output:
# A tibble: 2 x 3
Name Age Score
1 Alice 25 90
2 Bob 30 85
[1] 25 30
Factors
Factors represent categorical data in R. They store unique levels. This is useful for modeling and plotting. Use factor() to create factors. Factors prevent storing repeated strings. They can be ordered or unordered. Use levels() and relevel() to modify levels.
# Creating a factor
colors <- factor(c("Red", "Blue", "Red", "Green", "Blue"))
print(colors)
# Viewing levels
levels(colors)
# Changing levels
colors <- relevel(colors, ref = "Green")
Output:
[1] Red Blue Red Green Blue Levels: Blue Green Red [1] "Blue" "Green" "Red"
Conclusion
R has several data structures for handling data. Vectors, lists, arrays, and matrices store numerical and multi-dimensional numerical data. Data frames and tibbles are useful for data analysis. They allow storage of different data types in a tabular format. Factors help manage categorical data. Choosing the right structure depends on the data and how you want to use it. Knowing these structures helps in working with data in R.
For more advanced topics, consider exploring additional resources on R programming and data analysis techniques, such as the official R documentation or other R content on Statology.
