I'd like to parallelize a period.apply function in R, I'm trying to use doParallel
with Foreach
, but I don't know how i could implement this function. The data I'm using is an xts
object with the date time index and the values of a variable, and what I am trying to do is make the mean of the data every 5 seconds:
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
Here is a sample of the code I wrote but it doesn't work:
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()
The code that works is this but for a much bigger database it takes too much time:
ends <- endpoints(x,"secs",5)
m <- period.apply(x, ends, mean)
index(m) <- trunc(index(m),"secs")
Is there a way of doing this more efficiently?
Thanks in advance.