简体   繁体   中英

In R how can I make the for loop run faster?

I have the below code, of 2 time series. maxNo is the number of elements in the time series. longStopPrev is the 1 position lagged version of longStop. The variables are initiated before the loop so that their size is not increasing in every iteration. When the maxNo is large, this loop takes a very long time to run.

Is there any clever way to avoid using for loop and vectorize or to make this run faster?

I think the main challenge is that there is a chance for the variable longStopPrev to be changed in each run of the loop, which makes it hard to run the operations only one time as a vector. However there could be a better way to execute, similar to different search algorithms.

I have tested using foreach but it only made the code run slower. I have also tested changing inside the for loop

longStopPrev = stats::lag(longStop, k=1,na.pad = TRUE) # lag 1 

with:

longStopPrev[i+1] <- longStop[i]

But the result was slightly slower.

I tried to make a reproducible example below. I test the code with ~10.000 points in my time series and actually want to run with ~100.000 or longer.

require("xts")

set.seed(47); n = 1e1;
data <- xts(rnorm(n)+10, 
             order.by = seq(as.POSIXct("2017-05-31 17:00:00"), length=n, by="min"))

diff=0.5
longStop = data - diff

longStopPrev = stats::lag(longStop, k=1,na.pad = TRUE) # lag 1
longStopPrev = na.approx(longStopPrev, rule=2,na.rm = FALSE,maxgap=1) # fill NA values by approx

maxNo <- nrow(longStop)

for(i in 1:maxNo) {
  if(as.numeric(data[i])>as.numeric(longStopPrev[i]) ){
    longStop[i] <- max(longStop[i],longStopPrev[i])
    longStopPrev = stats::lag(longStop, k=1,na.pad = TRUE) # lag 1 
    
  }
}
longStopPrev = na.approx(longStopPrev, rule=2,na.rm = FALSE,maxgap=1) # fill NA values by approx

I found out that converting xts to a matrix before the for loop using coredata() speeds up the code a lot. Apparently calling xts elements is much slower compared to a matrix. at the end of the for loop you can just convert back to xts if you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM