0

I'm having a data table, which can look like this:

year <- c("2018", "2018", "2018", "2018")
month <- c("01","01","01","01")
day <- c("01", "02","03","04")
hour <- c("00","01","02","03")
id <- c(8750, 3048, 3593, 8475)
type <- c("ist","plan","ist","plan")

dt.test <- data.table(year, month, day, hour, id, type)

Now I want to combine the columns year, month, day and hour to a single column called date of the form "2018-01-01 00", "2018-01-02 01" and so on. In the end I need a data table with the columns date (combined one), id and type. I know how to do this with paste(), but is there another fast and efficient way to do so?

George
  • 19,234
  • 7
  • 57
  • 99
MikiK
  • 318
  • 2
  • 14

1 Answers1

1

You may use tidyr::unite -

dt.test <- tidyr::unite(dt.test, date, year:hour, sep = '-')
dt.test

#            date   id type
#1: 2018-01-01-00 8750  ist
#2: 2018-01-02-01 3048 plan
#3: 2018-01-03-02 3593  ist
#4: 2018-01-04-03 8475 plan
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
  • 1
    This doesn't give the format as specified though - there's a space between the day and the hour instead of a dash. That'll contribute quite a bit because you only need one paste operation as opposed to two. – thelatemail Aug 04 '21 at 06:50
  • If you have [a look under the hood](https://github.com/tidyverse/tidyr/blob/master/R/unite.R) `unite` boils down to `paste` and `paste0`. – Henrik Aug 04 '21 at 10:20