tidyr unpack() in R: Spread df-Column Back Into Columns
The unpack() function in tidyr expands a packed df-column (a column whose cells are tibbles) back into multiple top-level columns. It is the opposite of pack().
df |> unpack(packed_col) # spread back to columns df |> unpack(c(col1, col2)) # multiple packed cols df |> unpack(packed_col, names_sep = "_") df |> pack(...) # opposite operation
Need explanation? Read on for examples and pitfalls.
What unpack() does in one sentence
unpack(data, cols, names_sep = NULL) expands a column whose cells are tibbles into multiple top-level columns. The new columns are named after the inner tibble's columns.
Syntax
unpack(data, cols, ..., names_sep = NULL, names_repair = "check_unique").
pack(...) |> unpack(...) returns the original data frame.Five common patterns
1. Standard unpack
2. Multiple df-columns
3. With names_sep
4. Round-trip
5. Selective unpack
unpack expects DF-COLUMNS (tibble cells); unnest_wider accepts named lists too. They overlap but unpack is specifically for the column-of-tibbles structure created by pack.unpack() vs unnest_wider() vs unnest()
| Function | Input cell type | Output |
|---|---|---|
unpack() |
Tibble (one row per cell) | New columns |
unnest_wider() |
Named list or 1-row tibble | New columns |
unnest() |
Tibble (multiple rows) | New rows |
Use unpack for pack/unpack round-trips; unnest_wider for general named-list structures.
A practical workflow
Use unpack to undo pack-style organization for downstream verbs that don't understand df-columns.
Unpack for filter; re-pack after.
Common pitfalls
Pitfall 1: name conflicts. If unpacking creates duplicate names with existing columns, error. Use names_sep or names_repair.
Pitfall 2: confusing with unnest. unpack is for SINGLE-ROW tibble columns. unnest is for MULTI-ROW tibble columns.
unpack() requires each cell to be a tibble of the same shape. Inconsistent shapes error.Try it yourself
Try it: Pack then unpack mtcars and verify identity. Save check to ex_check.
Click to reveal solution
Explanation: pack/unpack are inverses; round-trip preserves the data exactly.
Related tidyr functions
After mastering unpack, look at:
pack(): opposite (combine columns)unnest(): list-column to rowsunnest_wider(): named lists to columnsunnest_longer(): vectors to rows
FAQ
What does unpack do in tidyr?
unpack(data, col) expands a column whose cells are tibbles into multiple top-level columns.
What is the difference between unpack and unnest_wider?
unpack expects df-columns (tibble cells with one row each). unnest_wider also accepts named lists. unpack is more strict.
How do I avoid name conflicts when unpacking?
Pass names_sep = "_" to prefix the new columns with the original df-column's name.
Is unpack the inverse of pack?
Yes. pack(...) |> unpack(...) returns the original.
Can I unpack multiple df-columns at once?
Yes. unpack(c(col1, col2)) unpacks both. Each cell must be a tibble.