一般如链接中所述,xts 是处理时间序列的好包。另一种选择是使用data.table 包。这里我比较了 2 个包的性能计算时间序列的每日平均值。
## needed package
library(data.table)
library(xts)
library(microbenchmark)
## create the data, here I am using yearly index with half an hour frequency
set.seed(1)
time = seq.POSIXt(from=as.POSIXct('2013-01-01',tz=''),
to=as.POSIXct('2013-12-31',tz=''),
by = as.difftime(0.5,units="hours"))
value= runif(n = length(time), min = 18, max = 54)
## the data.table object
DT <- data.table(time=time,value=value)
## the time series
xtt <- xts(x=value,time)
我使用 data.table 和 xts 计算每日平均值。对于 data.table,我使用 2 种方法:第一种方法创建分组因子 (day),第二种方法使用已经创建的分组因子。
## compute daily mean using data.table
dt.m <- function()
DT[,day:=format(time,'%d-%m-%Y')][,mean(value),day]
## using data.table but the grouping variable is already created
dt.withday.m <- function()
DT[,mean(value),day]
## daily mean using time series
xts.m <- function()
xtt.d <- apply.daily(xtt,mean)
## benchmark
microbenchmark(dt.m(),xts.m(),dt.withday.m,times=5,unit='ms')
Unit: milliseconds
expr min lq median uq max neval
dt.m() 159.36342 160.71548 161.628732 162.527193 171.672999 5
xts.m() 206.63565 207.90692 208.210708 214.023594 225.322446 5
dt.withday.m 0.00038 0.00038 0.001138 0.001139 0.001518 5
所以这两种方法的性能几乎相同。但是一旦我们创建了分组因子(dt.withday.m),我们就会显着提高性能。所以如果你必须做其他日常总结,使用data.table是最好的选择。
另一点是rolling 平均值或在给定宽度时间窗口内计算平均值。据我所知,我认为 xts 在滚动平均值方面是无与伦比的:
xtt.r <- rollapply(xtt,width=2,FUN=mean)