如何将两列或多列数据table合并为一列?

How to combine two or more columns of data table to one column?

我有一个数据 table,它看起来像这样:

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)

现在我想将列 yearmonthdayhour 合并为一个名为 date 的列,格式为 "2018-01-01 00""2018-01-02 01" 等等。最后,我需要一个数据 table,其中包含列 date(组合一个)、idtype。我知道如何使用 paste() 来做到这一点,但是还有另一种快速有效的方法吗?

您可以使用 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