【发布时间】:2018-10-08 07:49:08
【问题描述】:
我想在 R 中并行化 period.apply 函数,我正在尝试使用 doParallel 和 Foreach,但我不知道如何实现这个函数。我使用的数据是带有日期时间索引和变量值的xts 对象,我想做的是每 5 秒取一次数据的平均值:
VAR
2018-01-01 00:00:00 1945.054
2018-01-01 00:00:02 1944.940
2018-01-01 00:00:05 1945.061
2018-01-01 00:00:07 1945.255
2018-01-01 00:00:10 1945.007
2018-01-01 00:00:12 1944.995
这是我编写的代码示例,但它不起作用:
library(xts)
library(doParallel)
library(foreach)
cores <- detectCores()
cluster <- makeCluster(cores, type = "PSOCK")
registerDoParallel(cluster)
ends <- endpoints(x,"secs",5)
m <- foreach(i = 1:length(index(x))) %dopar% period.apply(x,ends,mean)
index(m) <- foreach(m) %dopar% trunc(index(m),"secs")
stopCluster()
有效的代码是这样的,但对于更大的数据库,它需要太多时间:
ends <- endpoints(x,"secs",5)
m <- period.apply(x, ends, mean)
index(m) <- trunc(index(m),"secs")
有没有更有效的方法?
提前致谢。
【问题讨论】:
-
读者不清楚
period.apply()是 'xts' 中的一个函数 - 请更新为library(xts)。 -
关于“不起作用”,您是否收到错误消息,或者它给您错误的结果,或者它只是没有更快?
-
执行时间太长,我应该停止执行。
-
@Riverarodrigoa 您的方法是将任务拆分为(大约)N/5 个作业,每个作业只处理几行,其中 N 是您拥有的数据行数。更有效的是设置 8 个作业,每个作业处理 N/8 行。我看到 Ralf 的回答 stackoverflow.com/a/50090842/841830 就是这样做的。
标签: r foreach parallel-processing xts doparallel