你好,我正在寻找一种从data.table
中选择POSIXct
行的有效方法,以便一天中的时间小于12:00:00
(注意,毫秒不是必需的,因此我们可以使用ITime
)
set.seed(1); N = 1e7;
DT = data.table(dts = .POSIXct(1e5*rnorm(N), tz="GMT"))
DT
dts
# 1: 1969-12-31 06:35:54.618925
# 2: 1970-01-01 05:06:04.332422
# ---
# 9999999: 1970-01-03 00:37:00.035565
#10000000: 1969-12-30 08:30:23.624506
一种解决方案(这里的问题是,如果N很大,则强制转换可能会很昂贵)
f <- function(t, st, et) {time <- as.ITime(t); return(time>=as.ITime(st) & time<=as.ITime(et))}
P <- function(t, s) { #geekTrader solution
ep <- .parseISO8601(s)
if(grepl('T[0-9]{2}:[0-9]{2}:[0-9]{2}/T[0-9]{2}:[0-9]{2}:[0-9]{2}', s)){
first.time <- as.double(ep$first.time)
last.time <- as.double(ep$last.time)-31449600
SecOfDay <- as.double(t) %% 86400
return(SecOfDay >= first.time & SecOfDay <= last.time )
} else {
return(t >= ep$first.time & t <= ep$last.time)
}
}
快速查看性能
system.time(resf <- DT[f(dts,'00:00:00','11:59:59')])
user system elapsed
1.01 0.28 1.29
system.time(resP <- DT[P(dts,'T00:00:00/T11:59:59')])
user system elapsed
0.64 0.13 0.76
identical(resf,resP)
[1] TRUE
https://stackoverflow.com/questions/15830341
复制相似问题