Lists and Matrices in R Programming
1. Lists
Lists in R can store elements of different data types, such as numbers, strings, and even other lists.
Creating a List
# Creating a list
my_list <- list(
Name = "Alice",
Age = 25,
Scores = c(85, 90, 95)
)
# Printing the list
print(my_list)
Accessing List Elements
# Access an element by name
print(my_list$Name)
# Access an element by index
print(my_list[[2]])
# Access a specific part of an element (e.g., a vector inside the list)
print(my_list$Scores[1])
Modifying a List
# Add a new element to the list
my_list$Gender <- "Female"
print(my_list)
# Remove an element from the list
my_list$Age <- NULL
print(my_list)
2. Matrices
Matrices in R are two-dimensional arrays that can hold elements of the same data type.
Creating a Matrix
# Creating a matrix
my_matrix <- matrix(
data = 1:9, # Data values
nrow = 3, # Number of rows
ncol = 3, # Number of columns
byrow = TRUE # Fill the matrix by rows
)
# Printing the matrix
print(my_matrix)
Accessing Matrix Elements
# Access an element by row and column
print(my_matrix[2, 3])
# Access an entire row
print(my_matrix[1, ])
# Access an entire column
print(my_matrix[, 2])
Manipulating a Matrix
# Add a new row to the matrix
new_row <- c(10, 11, 12)
my_matrix <- rbind(my_matrix, new_row)
print(my_matrix)
# Add a new column to the matrix
new_col <- c(13, 14, 15, 16)
my_matrix <- cbind(my_matrix, new_col)
print(my_matrix)
Conclusion
This tutorial covered the creation and usage of lists and matrices in R. Lists are versatile and can store mixed data types, while matrices are ideal for numeric or character data in a two-dimensional format.