从日期和时间列中快速创建data.table中的时间戳

时间:2017-02-15 15:21:40

标签: r data.table

我有一个包含500多万行的数据集,我想从两列创建一个时间戳,一列有日期,另一列有时间值。

当我使用fread()函数将csv读入R时,所有列都是字符格式,因此我使用data.table将它们转换为相关格式,这对于那种事情非常快:

nf[, (dcols):= lapply(.SD,ymd),.SDcols=dcols] #using the ymd() function from lubridate to change date columns

我的下一步是创建一个时间戳,我按以下方式执行:

nf[,start_timestamp := as.POSIXct(paste(start_date,start_time))]

如果我在这个函数调用周围运行Sys.Time(),我会得到3.843分钟的时差。这是等待的时间,所以我想知道是否有人可以建议一个基于data.table的解决方案,这将允许我更快地将这两个列组合成一个时间戳?

1 个答案:

答案 0 :(得分:0)

使用fastPOSIXct包中的fasttime功能

可以更快地创建时间戳

Sample data

library(data.table)
library(fasttime)
library(lubridate)

ttfile <- "timestamp_test_data.csv"

tt <- read.table(ttfile, header = TRUE, stringsAsFactors = FALSE, sep=",",na.strings=c("NA","N/A","null"))

dcols <- c('start_date','end_date')
tcols <- c('start_time','end_time')

setDT(tt) #convert to data.table

tt[, (dcols):= lapply(.SD,mdy),.SDcols=dcols] # := updates the data table in place, no need to pass it to another vector
tt[, (tcols):= lapply(.SD,as.ITime),.SDcols=tcols]

tt[,start_timestamp := fastPOSIXct(paste(start_date,start_time - 3600))] #remove number of seconds in an hour to fix fastPOSIXct adding an hour to the timestamp - if it doesn't do that for you, just remove that part
tt[,end_timestamp := fastPOSIXct(paste(end_date,end_time - 3600))]

str(tt)