R Data Structures
Data Structures
Data structures are used to store and organize values.
R provides many built-in data structures. Each is used to handle data in different ways:
- Vectors
- Lists
- Matrices
- Arrays
- Data Frames
We will explore all of them in detail later, but for now, here's a quick introduction to each one.
Vectors
A vector is the most basic data structure in R. It contains a list of items of the same type.
Example
# Vector of strings
fruits <- c("banana", "apple", "orange")
# Print
fruits
fruits
Try it Yourself »
Lists
A list can hold different types of data in one structure. You can combine numbers, strings, vectors, and even other lists.
Example
# List of strings
thislist <- list("apple", "banana",
50, 100)
#
Print the list
thislist
Try it Yourself »
Matrices
A matrix is a 2D data structure where all elements are of the same type. It is like a table with rows and columns.
Example
# Create a matrix
thismatrix <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)
# Print the matrix
thismatrix
Try it Yourself »
Use nrow
and ncol
to control the size of the matrix.
Arrays
An array is like a matrix but can have more than two dimensions. It stores elements of the same type in multiple dimensions.
Example
# An array with one dimension with values ranging from 1 to 24
thisarray <-
c(1:24)
thisarray
# An array with more than one dimension
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray
Try it Yourself »
Arrays are useful for working with 3D or higher-dimensional data.
Data Frames
A data frame is like a table in a spreadsheet. It can hold different types of data across multiple columns.
Example
# Create a data frame
Data_Frame <- data.frame (
Training =
c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
# Print the data frame
Data_Frame
Try it Yourself »
Summary
Data Structure | Contains | Same Type? | Use Case |
---|---|---|---|
Vector | Single row of values | Yes | Simple sequences |
List | Multiple types | No | Grouped mixed data |
Matrix | 2D same-type values | Yes | Tables with numeric data |
Array | Multi-dimensional values | Yes | 3D or higher-dimensional data |
Data Frame | Columns of mixed types | No | Working with tabular data |
Next, let's take a closer look at each data structure in more detail.