The unite Function in R


The unite() method is used to merge two or more columns into a single column or variable. unite() generates a single data frame as output after merging the specified columns.

Let’s manually create a data frame.

id <- c(1:3)
year <- c(2010, 2010, 2011, 2011)
month <- c(2, 6, 1, 8)
day <- c(12, 30, 17, 3)
my_data <- data.frame(id, year, month, day)

Let’s use unite and pipes. We need to load the tidyverse.

library(tidyverse)
my_new_data <- my_data %>% 
  unite(date, year, month, day, remove=FALSE, sep = '-') %>%
  mutate(date = as.Date(date))

You can see below that we have indeed created a new column called date that is of type date.

> glimpse(my_new_data)
Rows: 4
Columns: 5
$ id    <int> 1, 2, 3, 4
$ date  <date> 2010-02-12, 2010-06-30, 2011-01-17, 2011-08-03
$ year  <dbl> 2010, 2010, 2011, 2011
$ month <dbl> 2, 6, 1, 8
$ day   <dbl> 12, 30, 17, 3

The separate function is the opposite of unite.

Learning with YouTube

Combining columns in R with unite().

Leave a Reply