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.

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

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

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

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

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