R’s true power comes from its rich set of built-in data structures. Choosing the right structure for your task not only streamlines code but also maximizes performance. In this section, we’ll dive deep into:
Vectors: the simplest one-dimensional object
Factors: efficient categorical data handling
Lists: heterogeneous collections for complex data
Matrices & Arrays: multi-dimensional atomic vectors
Data Frames & Tibbles: tabular data ready for analysis
1. Vectors: The Foundation
Vectors are R’s basic building blocks. A vector holds elements of a single type—numeric, character, or logical—and supports vectorized operations for speed and clarity.
# Creating vectors
numeric_vec <- c(10, 20, 30, 40)
char_vec <- c("red", "green", "blue")
logical_vec <- c(TRUE, FALSE, TRUE)
# Element-wise operations
numeric_vec * 2
# [1] 20 40 60 80
# Indexing and subsetting
numeric_vec[2] # 20
numeric_vec[numeric_vec > 25] # 30 40
Best practices:
Preallocate large vectors with
vector("double", length = n)to avoid repeated resizing.Use built-in functions (
sum(),mean(),sort()) to leverage optimized C code.
2. Factors: Categorical Data Handling
Factors map character values to integer codes under the hood, making them ideal for statistical models and memory efficiency.
# Creating a factor
responses <- c("yes", "no", "yes", "maybe", "no")
f_responses <- factor(responses, levels = c("yes", "no", "maybe"))
levels(f_responses)
# [1] "yes" "no" "maybe"
# Reordering levels
library(forcats)
f_responses <- fct_relevel(f_responses, "maybe", after = 0)
Key tips:
Always set
levels=explicitly to control the ordering.Use
forcats(part of the tidyverse) for advanced factor manipulation:fct_lump(),fct_recode(), and more.
3. Lists: Heterogeneous Collections
Lists are recursive, meaning they can hold elements of different types—including other lists. They’re perfect for nested data and function outputs.
# Creating a list
my_list <- list(
id = 1001,
scores = c(88, 92, 79),
info = list(name = "Alice", enrolled = TRUE)
)
# Accessing elements
my_list$id # 1001
my_list$scores[2] # 92
my_list$info$name # "Alice"
Use cases:
Storing model outputs (
lm()returns a list of components).Building custom objects in package development.
Passing around complex configurations.
4. Matrices & Arrays: Multi-Dimensional Atomic Data
Matrices extend vectors to two dimensions; arrays generalize to three or more. All elements must share the same type.
# Matrix creation (3 × 3)
m <- matrix(1:9, nrow = 3, byrow = TRUE)
# Array creation (2 × 3 × 2)
a <- array(1:12, dim = c(2, 3, 2))
# Indexing
m[2, 3] # Element in row 2, column 3
a[1, , 2] # First row across all columns in 3rd dimension
Performance tip:
Matrix algebra in R dispatches to optimized BLAS/LAPACK routines—use matrices for heavy linear algebra tasks.
5. Data Frames & Tibbles: Tabular Data
For most data analysis, you’ll work with tabular structures. Data frames allow columns of different types; tibbles (from the tibble package) offer a modern, user-friendly twist.
# Base data frame
df <- data.frame(
name = c("John", "Mary", "Sam"),
score = c(90, 85, 92),
passed = c(TRUE, TRUE, TRUE),
stringsAsFactors = FALSE
)
# Tibble
library(tibble)
tb <- tibble(
name = c("John", "Mary", "Sam"),
score = c(90L, 85L, 92L),
passed = c(TRUE, TRUE, TRUE)
)
# Printing behavior
df # prints all rows and columns
tb # shows dimensions and previews only first 10 rows/columns
Why choose tibbles?
Never convert strings to factors by default.
Automatic pretty-printing in the console.
Better support for non‐standard column names.
Conclusion and Next Steps
You’ve now explored R’s core data structures—from atomic vectors to rich tabular formats. Armed with this knowledge, you can select the optimal structure for any analysis, ensuring both clarity and performance. In the next section, we’ll dive into Importing and Exporting Data: reading CSVs, connecting databases, and writing outputs to streamline your workflows.
Have questions on these structures or want to share tips from your own experience? Drop a comment below and let’s continue the conversation!

Comments
Post a Comment