Skip to Content
Course content

49: tibble Package In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this exact scenario play out in code reviews more times than I can count. A developer spends weeks writing a script using base R data.frame objects, then decides to "modernize" the code by switching to tibble, and suddenly, their data processing pipeline just... stops working. They aren't getting a loud crash, but their calculations are returning NA or weird errors.

library(tibble)

# A simple dataset of sensor readings
readings <- tibble(
  sensor_id = 1:3,
  value = c(23.5, 25.2, 22.8)
)

# This function was written for base R data.frames
calculate_avg <- function(df) {
  # The dev wants the mean of the second column (value)
  mean(df[, 2]) 
}

calculate_avg(readings)
# Result: Warning: argument is not numeric or logical; returning NA

The Single-Column Subset Trap

If readings had been a standard data.frame, df[, 2] would have "dropped" the dimensions and returned a simple numeric vector. mean() loves vectors. But a tibble is designed to be consistent. When you subset a tibble with [ , ], it always returns another tibble, even if there is only one column left.

You're essentially trying to calculate the mean of a table, not the mean of the numbers inside the table. To fix this, you need to be explicit about wanting a vector. I usually recommend pull() from the dplyr ecosystem, but if you want to stay within the tibble mindset, use double brackets [[ ]].

# Fix 1: Using double brackets (the base R way that works for tibbles)
calculate_avg_fixed <- function(df) {
  mean(df[[2]]) 
}

# Fix 2: Using pull() (the tidyverse way)
library(dplyr)
calculate_avg_tidy <- function(df) {
  mean(pull(df, value))
}

calculate_avg_fixed(readings) # 23.83333

Creating Data Manually with tribble

Most of the time, you're loading CSVs or SQL queries. But sometimes you need to hard-code a small lookup table or a set of parameters directly into your script. Writing tibble(col1 = c(...), col2 = c(...)) is tedious and hard to read. This is where tribble() (transposed tibble) comes in.

I love tribble() because it lets you lay out the data exactly how it will look in the final table. It's much more intuitive for anyone reading your code later.

# Imagine we're setting up a conversion rate table
conversion_rates <- tribble(
  ~currency, ~rate, ~symbol,
  "USD",     1.0,   "$",
  "EUR",     0.92,  "€",
  "GBP",     0.79,  "£"
)

print(conversion_rates)

Strictness as a Feature

You might find tibbles "annoying" because they don't allow partial matching. In base R, if you have a column named temperature_celsius, you can actually access it using df$temp and R will guess what you mean. Tibbles refuse to do this. They will return NULL instead.

This feels like a hurdle at first, but in a production environment, partial matching is a liability. It's far better for your code to fail immediately because of a typo than to silently grab the wrong column because it "looked close enough." When you're writing professional software, explicit is always better than implicit.

Handling Column Names and Types

One last thing to keep in mind: tibbles never change the type of your input. If you pass a character vector into a tibble, it stays a character vector. It doesn't try to be "helpful" by converting things into factors (which was a huge headache in older versions of base R).

If you find yourself needing to clean up messy column names—like those annoying spaces or special characters that come from Excel imports—don't do it manually. While tibble provides the structure, I always pair it with the janitor package's clean_names() function to ensure my column headers are programmatically friendly.




📋 Practical Task

Exercise: Building a Project Resource Matrix

You are tasked with creating a small reference table for a project management tool. Instead of loading a file, you need to hard-code this data into your script for portability.

Requirements:

  • Use the tribble() function to create a tibble named team_resources.
  • The table must have three columns: staff_name (character), role (character), and hourly_rate (numeric).
  • Add at least three rows of data (e.g., "Alice", "Lead Dev", 150).
  • Once the tibble is created, write a line of code that extracts the hourly_rate column as a numeric vector (not a tibble) and calculates the average rate using mean().

Expected Output: A single numeric value representing the average of the rates you entered.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.