name height weight
1 Ada 64 135
2 Bob 74 156
3 Chris 69 139
4 Diya 69 144
5 Emma 71 152
Data Wrangling: data frames
Wednesday, 19 August 2026
In section of the data wrangling topic you will
Understand how to create data frames
How to access the elements of data frames
Create and work with tibbles
Data frames are R’s equivalent of an Excel spreadsheet
Data are arranged in rows and columns
rows — observations
columns — variables
Data frames are a special case of a list, where each component of the list is required to be a vector of the same length
Each column of the data frame can be of a difference type
Use the data.frame() function
There are many functions for working with data frames
Useful functions include
head()tail()nrow()ncol()head() shows the first few rows of data frame (default is 6)
# A tibble: 5 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
# ℹ 2 more variables: sex <fct>, year <int>
tail() works similarly, but shows the last n rows.
Can appear complicated because data frames are lists and matrix-like objects
Matrix-like access
Can use:
row names and column names — people['Ada', 'height']
row & column number (index) — people[2, 3]
mixtures — people[2, 'height']
extracting one or more rows — people[2, ]
extracting one or more columns — people[, 'height']
Can use numeric, character, logical indices
Tibbles are a modern implementation of the data frame concept
Widely used in the Tidyverse — a collection of packages that all share common philosophy and approaches to working with data
Coerce a data frame to be a tibble with as_tibble() (from tibble 📦)
Load data directly to tibbles using the readr, vroom, & readxl 📦📦📦
# A tibble: 344 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
7 Adelie Torgersen 38.9 17.8 181 3625
8 Adelie Torgersen 39.2 19.6 195 4675
9 Adelie Torgersen 34.1 18.1 193 3475
10 Adelie Torgersen 42 20.2 190 4250
# ℹ 334 more rows
# ℹ 2 more variables: sex <fct>, year <int>
There are some differences
people$name extracts a vector as usual but never partial matches — people$nam is an error
people[ , "height"] extracts a 1-column data frame — [r, c] never drops empty dimensions
tibbles are much faster for large data sets
tibbles print differently — never again swamp your R session by accidentally printing a large data frame