0Pricing
R Academy · Lesson

separate() and unite() for String Columns

Split and merge column values containing multiple pieces of information.

separate() and unite() for String Columns is a free R Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Splitting and Combining String Columns

Raw data often has multiple pieces of information crammed into a single column (e.g., '2024-03-15' contains year, month, and day). tidyr's separate() and unite() functions split one column into many, or combine many into one.

library(tidyr)

# Date stored as a single string column
df <- data.frame(
  id = 1:4,
  date = c('2024-01-15','2024-03-22','2023-11-08','2024-06-30'),
  value = c(100, 200, 150, 175)
)

print(df)

separate() — Split One Column into Many

separate(df, col, into, sep) splits a character column into multiple new columns using a separator. The into argument names the new columns; sep is the delimiter (default: any non-alphanumeric character).

library(tidyr)

df <- data.frame(
  id = 1:4,
  date = c('2024-01-15','2024-03-22','2023-11-08','2024-06-30')
)

# Split 'date' into year, month, day
separate(
  df,
  col = date,
  into = c('year','month','day'),
  sep = '-'
)

separate() with convert Argument

By default, separate() creates character columns. Set convert = TRUE to automatically convert the new columns to the most appropriate type (integer, numeric, logical). This is especially useful for year and month columns.

library(tidyr)

df <- data.frame(
  event = c('2024-1','2024-2','2023-12'),
  score = c(85, 90, 78)
)

result <- separate(
  df,
  col = event,
  into = c('year','month'),
  sep = '-',
  convert = TRUE
)

print(result)
cat('year type:', class(result$year), '\n')
cat('month type:', class(result$month))

separate() with remove = FALSE

By default separate() removes the original column. Set remove = FALSE to keep it alongside the new split columns. This is useful when you want to verify the split or keep the original for reference.

library(tidyr)

df <- data.frame(
  full_code = c('US-CA-001','US-TX-002','UK-LDN-003')
)

separate(
  df,
  col = full_code,
  into = c('country','state','code'),
  sep = '-',
  remove = FALSE   # Keep original column
)

separate() on Fixed Positions

Instead of a delimiter, you can split at fixed character positions by passing an integer vector to sep. Positive integers count from the left; negative integers count from the right.

library(tidyr)

# Product code: first 3 chars = category, next 4 = id
df <- data.frame(
  code = c('ABC1234','XYZ5678','DEF9012'),
  qty = c(10, 20, 15)
)

separate(
  df,
  col = code,
  into = c('category','product_id'),
  sep = 3    # Split after position 3
)

unite() — Combine Columns into One

unite(df, col, ..., sep) combines multiple columns into a single character column. The first argument after df is the new column name, followed by the columns to combine, then the separator string.

library(tidyr)

df <- data.frame(
  first = c('Alice','Bob','Carol'),
  last = c('Smith','Jones','White'),
  score = c(85, 90, 78)
)

unite(
  df,
  col = 'full_name',
  first, last,
  sep = ' '
)

unite() with remove = FALSE

Like separate(), unite() removes the source columns by default. Set remove = FALSE to retain the original columns alongside the new combined column. Useful when you need both forms.

library(tidyr)

df <- data.frame(
  year = c(2024, 2024, 2023),
  month = c(1, 3, 12),
  day = c(15, 22, 8)
)

unite(
  df,
  col = 'date_str',
  year, month, day,
  sep = '-',
  remove = FALSE
)

unite() to Build Keys

A common use of unite() is creating composite keys by combining multiple identifier columns. This is useful before joining tables that need a shared key built from multiple fields.

library(tidyr)
library(dplyr)

orders <- data.frame(
  year = c(2024, 2024, 2023),
  region = c('East','West','East'),
  seq_num = c(1, 1, 2)
)

orders_keyed <- orders %>%
  unite(col = 'order_key', year, region, seq_num, sep = '_')

print(orders_keyed)

separate_rows() — Split to Multiple Rows

separate_rows(df, col, sep) splits a cell containing multiple values into separate rows. This is different from separate() which splits to columns. It's useful when a cell contains a comma-separated list of items.

library(tidyr)

# Tags stored as comma-separated values in one cell
df <- data.frame(
  id = 1:3,
  title = c('Intro to R','Data Viz','ML Basics'),
  tags = c('r,beginner','r,ggplot,visualization','r,ml,modeling')
)

separate_rows(df, tags, sep = ',')

Chaining separate() and unite()

You can chain separate() and unite() in a pipeline to reformat date strings, fix inconsistent formats, or create new composite identifiers from existing columns.

library(tidyr)
library(dplyr)

# Reformat date from YYYY-MM-DD to DD/MM/YYYY
df <- data.frame(
  id = 1:3,
  date = c('2024-01-15','2024-03-22','2023-11-08')
)

df %>%
  separate(date, into=c('year','month','day'), sep='-') %>%
  unite(col='date_eu', day, month, year, sep='/')

Handling Extra or Missing Pieces

separate() has an extra argument for when there are more pieces than into columns: 'warn' (default), 'drop' (discard extras), or 'merge' (keep last piece unsplit). Similarly, fill handles fewer pieces: 'warn', 'right', or 'left'.

library(tidyr)

# Inconsistent data: some rows have 2 parts, some have 3
df <- data.frame(
  code = c('A-1','B-2-extra','C-3'),
  value = c(10, 20, 30)
)

# 'merge' keeps the last piece unsplit
separate(df, code, into=c('prefix','suffix'), sep='-',
         extra='merge')

Quick Check

Which function would you use to split rows where a column contains comma-separated values like 'tag1,tag2,tag3' into one row per tag?

Recap: separate() and unite()

Key takeaways for separate() and unite():

  • separate(col, into, sep) — split one column into multiple columns by delimiter or position
  • convert = TRUE — automatically type-convert the split results
  • remove = FALSE — keep the original column in both functions
  • unite(col, ..., sep) — combine multiple columns into one string column
  • separate_rows(col, sep) — split delimited values into multiple rows (not columns)
  • extra and fill arguments handle inconsistent split results
library(tidyr)
library(dplyr)

df <- data.frame(
  id = 1:3,
  datetime = c('2024-01-15 09:30','2024-03-22 14:15','2023-11-08 11:45')
)

df %>%
  separate(datetime, into=c('date','time'), sep=' ') %>%
  separate(date, into=c('year','month','day'), sep='-', convert=TRUE) %>%
  separate(time, into=c('hour','minute'), sep=':', convert=TRUE)

Frequently asked questions

Is the “separate() and unite() for String Columns” lesson free?

Yes — the full text of “separate() and unite() for String Columns” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “separate() and unite() for String Columns”?

Split and merge column values containing multiple pieces of information. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “separate() and unite() for String Columns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Wide to Long with pivot_longer()
  2. Long to Wide with pivot_wider()
  3. separate() and unite() for String Columns
  4. Nesting and Unnesting Data Frames
← Back to R Academy