separate() and unite() for String Columns
Split and merge column values containing multiple pieces of information.
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 = '-'
)All lessons in this course
- Wide to Long with pivot_longer()
- Long to Wide with pivot_wider()
- separate() and unite() for String Columns
- Nesting and Unnesting Data Frames