次のようないくつかのエントリを含むファイルがあるとします。
02/10/11 10:26:35 AM UTC, 0
02/10/11 10:26:38 AM UTC, 1
02/10/11 10:26:42 AM UTC, 0
R
で、この情報を完全な長さのバイナリ時系列 (1 秒のサンプリング間隔を想定) に変換し、0 と 1 で代入する簡単な方法はありますか?
この例では、系列は次のようになります: 0 0 0 1 1 1 1 0
編集: Dirk と Josh が独自のソリューションを提供したため、処理時間の観点からそれらを比較したいと思いました。
library(xts)
library(data.table)
library(rbenchmark)
doseq <- function(N,Nby){
base.t <<- Sys.time()
t.seq <<- base.t + seq.int(from=0, to=N, by=Nby)
n.t <<- length(t.seq)
val.seq <<- (1:n.t - 1) %% 2
}
josh <- function(N,Nby=10){
doseq(N,Nby)
dt1 <- data.table(time = t.seq, val=val.seq, key="time")
dt2 <- data.table(time = with(dt1, seq(min(time), max(time), by=1)), key = "time")
dtf <- dt1[dt2, rolltolast = TRUE]
return(dtf)
}
dirk <- function(N,Nby=10){
doseq(N,Nby)
xt1 <- xts(val.seq, t.seq)
secs <- seq(start(xt1), end(xt1), by="1 sec")
xtf <- zoo::na.locf(merge(xt1, xts(, secs)))
return(xtf)
}
bm <- benchmark(josh(1e2,10), josh(1e3,10), josh(1e4,10), josh(1e5,10), josh(1e6,10),
dirk(1e2,10), dirk(1e3,10), dirk(1e4,10), dirk(1e5,10), dirk(1e6,10),
columns=c("test", "replications","elapsed", "relative"),
replications=10)
print(bm)
与える:
test replications elapsed relative
6 dirk(100, 10) 10 0.024 1.000
7 dirk(1000, 10) 10 0.026 1.083
8 dirk(10000, 10) 10 0.044 1.833
9 dirk(1e+05, 10) 10 0.321 13.375
10 dirk(1e+06, 10) 10 3.342 139.250
1 josh(100, 10) 10 0.034 1.417
2 josh(1000, 10) 10 0.036 1.500
3 josh(10000, 10) 10 0.070 2.917
4 josh(1e+05, 10) 10 0.453 18.875
5 josh(1e+06, 10) 10 5.381 224.208
それほど違いはないように見えますが、xts
方法は方法よりもいくらか高速ですdata.table
。