【发布时间】:2013-03-27 15:45:47
【问题描述】:
您好,我正在寻找一种从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
【问题讨论】:
-
您是否乐意创建一个
itime列并以此为关键字? -
@mnel: 是的,所以我们进行二分搜索...
-
你真的不应该在你的问题中编辑别人的答案
-
我明白了……这是为什么呢?看起来更适合我理解......
-
@statquant :只是好奇为什么里奇的答案会获得赏金?
标签: r time-series data.table posixct subset