tidyr Separate and Unite

Data ManipulationtidyrFree Lesson

Advertisement

Introduction

separate() splits a column into multiple columns. unite() combines multiple columns into one.

Separate

library(tidyr)

df <- tibble(
  id = 1:3,
  date = c("2024-01-15", "2024-02-20", "2024-03-25")
)

# Split into year, month, day
df %>%
  separate(date, into = c("year", "month", "day"), 
           sep = "-")

Separate with Position

df <- tibble(
  id = 1:3,
  code = c("A123", "B456", "C789")
)

# Split by position
df %>%
  separate(code, into = c("letter", "number"),
           sep = 1)

Unite

df <- tibble(
  year = c(2024, 2024),
  month = c("01", "02"),
  day = c("15", "20")
)

# Combine columns
df %>%
  unite("date", year, month, day, sep = "-")

Summary

separate() and unite() handle column transformations. Use sep appropriately for splitting/joining.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement