Separate Function in R


The separate function in R will take a column’s data and separate it into multiple columns. One easy example to think about is a column called FullName that can be separated into FirstName and LastName.

Separate Function

We will separate the names in the example below. separate() is in the tidyverse package, so be sure to load it with library(tidyverse). The whole code chunk is provided below. Here’s more information in the R documentation. The separate function is used when you are transforming data.

id <- c(1:3)
name <- c("Susan Smith", "Rachel Hickman", "Bob Johnson")
job_title <- c("Clerical", "President", "Management")
salary <- c("45000", "90000", "68000") 
employee <- data.frame(id, name, job_title, salary)
print(employee)
library(tidyr)
separate(employee, name, into=c('first_name', 'last_name'), sep=' ')
print(employee)
employee2 <- separate(employee, name, into=c('first_name', 'last_name'), sep=' ')
print(employee2)

Here’s what it looks like at the console.

The separate function has a partner function called unite.

Excel

In Excel’s Power Query you can split columns by a delimiter.

Leave a comment

Your email address will not be published. Required fields are marked *