在更短的时间内将秒间隔数据转换为每小时平均表示

Convert seconds interval data to hourly mean representation in LESS TIME

我有一个数据文件,其中包含以 30 秒持续时间采样的读数。文件组织是:

> head(dframe)
            timestamp    power
1 2015-08-01 00:00:04 584.1379
2 2015-08-01 00:00:34 585.8087
3 2015-08-01 00:01:04 584.9335
4 2015-08-01 00:01:34 584.4366
5 2015-08-01 00:02:04 584.2829

现在将 30 秒持续时间数据表示为每小时意味着我使用以下 R 命令:

df = aggregate(list(power=dframe$power),by=list(timestamp=cut(as.POSIXct(dframe$timestamp),"hour")),mean) 

这非常有效。但是,实际问题在于大文件(一年的数据)所需的时间。我能以某种方式减少转换过程所需的时间吗?换句话说,在 R 中,是否有任何其他最佳选择可以花费更少的时间将秒数据转换为每小时平均数据?

更新: 对于@akrun 和@Joshua 建议的同一问题,我使用了 4 种不同的方法。对于堆栈溢出的其他用户,我在这里提供所有方法的用法和各自花费的时间

dframe<-read.csv(path,head=TRUE,sep=",")
dframe$timestamp<- as.POSIXct(dframe$timestamp)
xframe = dframe
#using aggregate
system.time(
df1<- aggregate(list(power=dframe$power),by=list(timestamp=cut(dframe$timestamp,"hour")),mean)
)
# using data.table
system.time(
dfx<-setDT(dframe)[, list(power= mean(power)) ,(timestamp= cut(timestamp, 'hour'))]
)
# using dplyr
system.time( 
xframe %>% group_by(timestamp= cut(timestamp, 'hour')) %>% summarise(power=mean(power))
)
#using xts
system.time({
  x <- xts(dframe$power,dframe$timestamp)
  h <- period.apply(x, endpoints(x, "hours"), mean)
  h <- data.frame(timestamp=trunc(index(h),'hours'), power=coredata(h))
})

两个(一个月,三个月)不同的数据集分别花费的时间是:对于一个月的数据集:

Method       user  system elapsed 
Aggregate    0.137   0.005   0.142
data.table   0.031   0.001   0.032 
dplyr        0.035   0.001   0.036  
xts          0.053   0.000   0.053  

对于三个月的数据集:

Aggregate    0.456   0.019   0.475 
data.table   0.099   0.002   0.102  
dplyr        0.099   0.004   0.103  
xts          0.158   0.004   0.161

警告:除xts 之外的所有方法都会将时间戳类型从POSIXct 更改为Factor。这意味着您必须再次转换时间戳列的类型,这将导致更多 cpu 周期。简而言之,如果最后你还需要 POSIXct 时间戳,那么 xts 是最好的,否则就去 data.table.

DATASET 使用的数据集可以在 link

找到

总的来说,aggregate 比较慢。我们可以使用 data.table 来加快速度。将'data.frame'转换为'data.table'(setDT(dframe)),我们用cut从'timestamp'创建分组变量,得到mean 21=].

library(data.table)
setDT(dframe)[, list(power= mean(power)) ,(timestamp= cut(as.POSIXct(timestamp), 'hour'))]

使用 xts 包中的工具,您可以在不到一半的时间内完成此聚合。

# sample data
set.seed(21)
N <- 2e6
dframe <- data.frame(timestamp=seq(Sys.time(), by="30 sec", length.out=N),
                     power=rnorm(N))
# aggregate
system.time(a <- aggregate(list(power=dframe$power),by=list(timestamp=cut(dframe$timestamp,"hour")), mean))
#    user  system elapsed 
#   2.456   0.000   2.457 

# xts
system.time({
  x <- xts(dframe$power, dframe$timestamp)
  h <- period.apply(x, endpoints(x, "hours"), mean)
  h <- data.frame(timestamp=trunc(index(h),'hours'), power=coredata(h))
})
#    user  system elapsed 
#   0.888   0.004   0.893