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.
2 | year <- c(2010, 2010, 2011, 2011) |
5 | my_data <- data.frame(id, year, month, day) |
Let’s use unite and pipes. We need to load the tidyverse.
2 | my_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.
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().