r - 在 LESS TIME 中将秒间隔数据转换为每小时平均表示

标签 r time-series

我有一个数据文件,其中包含以 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 找到

最佳答案

使用 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 

关于r - 在 LESS TIME 中将秒间隔数据转换为每小时平均表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33207191/

相关文章:

c++ - stringstream 不适用于 OSX 10.6 上的 Rcpp

r - "select A, B, max(C) from D group by C"的 dplyr 习语

r - 如何从分组数据框中的每个组中获取每个第 n 个元素

r - Stargazer类型= "html"表输出中的列之间的空格

mysql 高效连接 2 个表到相同的 2 个表

r - 时间序列的快速傅里叶变换和聚类

RPostgreSQL 访问数据库,错误 : unable to find an inherited method for function "show", 签名 "PostgreSQLConnection"

r - 将每小时动物园时间序列输入函数 STL()

python - pandas中大数据集的数据准备

python - 使用 Pandas 计算 12 月 - 1 月 - 2 月平均值