01 / 20

separate() & unite()

Learn to split one column into many and combine many columns into one using the tidyr package in R.

R Programming tidyr

What is Tidy Data?

In R's tidyverse, tidy data follows three rules: each variable has its own column, each observation has its own row, and each value has its own cell. But real-world data is messy: sometimes two variables are crammed into one column, or one variable is spread across several.

Messy
A "date" column holds "2024-03-15": year, month, and day jammed together.
Tidy
Three columns: year, month, day, each holding one atomic value.

The tidyr Package

tidyr is part of the tidyverse: a collection of R packages designed for data science. It provides functions to reshape and tidy data frames. Two of the most useful are:

separate()
Splits one column into multiple columns by a delimiter or position.
unite()
Pastes multiple columns together into a single column with a separator.
# Load tidyr (or the whole tidyverse)
library(tidyr)

Why Separate and Unite?

Real datasets from surveys, APIs, and spreadsheets often pack multiple pieces of information into a single cell. Before you can filter, group, or visualize, you need to isolate each variable. Conversely, sometimes you need to create a composite key by joining columns together.

1
Filtering: separate a "city_state" column so you can filter by state alone.
2
Grouping: split "Q1-2024" into quarter and year to group by year.
3
Joining: unite first and last name into a full name for a merge key.

The separate() Function

separate(data, col, into, sep, remove, convert)
1
data: the data frame (or piped in with %>%).
2
col: the column to split (unquoted name).
3
into: a character vector of new column names, e.g. c("year", "month", "day").
4
sep: the delimiter (default: any non-alphanumeric character). Can be a regex or a numeric position.
5
remove: if TRUE (default), the original column is dropped.
6
convert: if TRUE, R will auto-detect types (e.g. character to integer).

The unite() Function

unite(data, col, ..., sep, remove)
1
data: the data frame (or piped in).
2
col: the name for the new combined column.
3
...: the columns to paste together (unquoted, comma-separated).
4
sep: the character to insert between values (default: "_").
5
remove: if TRUE (default), the original columns are dropped.

separate() vs unite(): Visual

separate() date 2024-03-15 year 2024 month 03 day 15 unite() first Ada last Lovelace full_name Ada_Lovelace 1 column → 3 columns 2 columns → 1 column ← Inverse operations →

sep: Character vs Position

The sep argument in separate() can take two types of values, and they behave very differently:

Character sep Numeric sep
Type String or regex Integer(s)
How it works Splits at the delimiter Splits at character position(s)
Example sep = "-" sep = c(4, 6)
Input: "20240315" Cannot split (no dash) "2024", "03", "15"
Input: "2024-03-15" "2024", "03", "15" "2024", "-0", "3-15"

How to Apply These Functions

1
Inspect your data: look at the column values. Are multiple variables crammed into one cell, or do you need to combine cells?
2
Choose your function: use separate() to split, unite() to combine.
3
Identify the separator: what character sits between the values? A dash, underscore, slash, space? Or is it fixed-width?
4
Name the result columns: for separate(), provide into = c("name1", "name2"). For unite(), choose the new column name.
5
Set convert = TRUE if you want R to auto-detect numeric types after splitting (separate only).

Example 1: Splitting Dates

Given a data frame with a combined "date" column, split it into year, month, and day:

# Original data
df <- tibble(date = c("2024-03-15", "2023-11-02"))

# Separate the date column
df %>%
  separate(col = date,
           into = c("year", "month", "day"),
           sep = "-")
yearmonthday
20240315
20231102

Example 2: Combining Names

Given separate first and last name columns, create a single "full_name" column:

# Original data
df <- tibble(first = c("Ada", "Alan"),
           last = c("Lovelace", "Turing"))

# Unite first and last into full_name
df %>%
  unite(col = "full_name",
        first, last,
        sep = " ")
full_name
Ada Lovelace
Alan Turing

Example 3: convert and remove

Split a "score" column and keep the original, while converting the results to proper types:

df <- tibble(score = c("math-95", "reading-88"))

df %>%
  separate(col = score,
           into = c("subject", "points"),
           sep = "-",
           remove = FALSE,
           convert = TRUE)
scoresubjectpoints
math-95math95
reading-88reading88

Example 4: Chaining Both Together

You can separate and then unite in a single pipeline to restructure data:

df <- tibble(date = c("2024-03-15", "2023-11-02"))

# Split date, then recombine as month/year
df %>%
  separate(date, c("year", "month", "day"), "-") %>%
  unite("month_year", month, year, sep = "/")
month_yearday
03/202415
11/202302

Common Mistakes

✕ Wrong number of pieces
If your into vector has 3 names but a value only splits into 2 pieces, you get NA in the third column and a warning.
✕ Forgetting sep in unite()
The default separator in unite() is "_". If you want a space or dash, you must explicitly set sep.
✕ Quoting column names
In separate(), the col argument is unquoted: col = date, not col = "date". But into takes quoted strings.

Summary Comparison

separate() unite()
Direction 1 column → many Many columns → 1
Key argument into (new names) col (new name)
Default sep Any non-alphanumeric "_"
convert arg? Yes No
remove default TRUE TRUE
Inverse of unite() separate()

Question 1 of 5

What does separate() do to a data frame?

Question 2 of 5

Which argument in separate() provides the names for the new columns?

Question 3 of 5

What is the default separator used by unite()?

Question 4 of 5

You run: df %>% separate(score, c("subject", "points"), sep = "-", convert = TRUE). If "score" contains "math-95", what type will the "points" column be?

Question 5 of 5

You have columns city and state. Which code correctly creates a "location" column with values like "Austin, TX"?