【发布时间】:2021-08-04 06:06:43
【问题描述】:
我有一个数据表,看起来像这样:
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)
现在我想将 year、month、day 和 hour 列合并为一个名为 date 的列,其形式为 "2018-01-01 00"、"2018-01-02 01" 等。最后,我需要一个包含date(组合一个)、id 和type 列的数据表。我知道如何使用paste() 来做到这一点,但还有其他快速有效的方法吗?
【问题讨论】:
-
paste应该很快。您如何使用它,您的数据有多大? -
我会像这样使用它:
dt.result$date1 <- paste(dt.test$year, dt.test$month, dt.test$day, sep = "-")dt.result$date <- paste(dt.result$date1, dt.test$hour)... 我的数据表大约是 1GB(我的行和列比我的问题示例多)。所以需要一些时间。 -
tidyr::unite有帮助吗?dt.test <- tidyr::unite(dt.test, date, year:hour, sep = '-') -
谢谢!这比我的
paste-version 快。 -
你有一个
data.table,那么为什么不通过引用来创建你的列呢?
标签: r datatable multiple-columns