Skip to main content

6 Core Data Structures: Vectors, Factors, Lists, Matrices, Arrays, Data Frames & Tibbles

 

R data structures, R vectors, R factors, R lists, R matrices, R arrays, R data frames, R tibbles

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.

r
# 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.

r
# 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.

r
# 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.

r
# 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.

r
# 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

Popular posts from this blog

Alfred Marshall – The Father of Modern Microeconomics

  Welcome back to the blog! Today we explore the life and legacy of Alfred Marshall (1842–1924) , the British economist who laid the foundations of modern microeconomics . His landmark book, Principles of Economics (1890), introduced core concepts like supply and demand , elasticity , and market equilibrium — ideas that continue to shape how we understand economics today. Who Was Alfred Marshall? Alfred Marshall was a professor at the University of Cambridge and a key figure in the development of neoclassical economics . He believed economics should be rigorous, mathematical, and practical , focusing on real-world issues like prices, wages, and consumer behavior. Marshall also emphasized that economics is ultimately about improving human well-being. Key Contributions 1. Supply and Demand Analysis Marshall was the first to clearly present supply and demand as intersecting curves on a graph. He showed how prices are determined by both what consumers are willing to pay (dem...

Fundamental Analysis Case Study NVIDIA

  Executive summary NVIDIA is analyzed here using the full fundamental framework: balance sheet, income statement, cash flow statement, valuation multiples, sector comparison, sensitivity scenarios, and investment checklist. The company shows exceptional profitability, strong cash generation, conservative liquidity and net cash, and premium valuation multiples justified only if high growth and margin profiles persist. Key investment considerations are growth sustainability in data center and AI, margin durability, geopolitical and supply risks, and valuation sensitivity to execution. The detailed numerical work below uses the exact metrics you provided. Company profile and market context Business model and market position Company NVIDIA Corporation, leader in GPUs, AI accelerators, and related software platforms. Core revenue streams : data center GPUs and systems, gaming GPUs, professional visualization, automotive, software and services. Strategic advantage : GPU architecture, C...

“This Sentence Is False”: The Liar Paradox, from Ancient Crete to Modern Code

 “All Cretans are liars,” said the Cretan Epimenides.  “This sentence is false,” echoes every logic textbook.  We’re still arguing 2,600 years later—and the paradox is winning.   _____________________________  /                             \ |   “THIS SENTENCE IS FALSE.”  |  \_____________________________/               |               |  self-reference               v    +---------------------------+    |  Truth flips back on     |    |  itself — paradox loop!  |    +---------------------------+ 1. Meet the Liar The classic one-liner: L: “This sentence is false.” If L is true, then what it asserts—its own falsity—must hold, so L is false. If L is false, then what it asserts isn’t the ca...