You can vectorize parts of this problem, especially if you need to find the starting position of the index in a (I called it str ) and the end of the window ( end ), but I have to use a loop construct to apply these index positions to a to take max using mapply . For instance:
x <- seq_len( length(a) ) end <- which( xb > 0 ) str <- end - b[end] res <- a res[ - end ] <- NA res[end] <- mapply( function(x,y) max( a[ x:y ] ) , str , end )
And comparing with @ e4e5f4 answer:
identical( res , out ) [1] TRUE
However, this is not so fast:
user system elapsed 0.46 0.00 0.47
If there was a way to vectorize the last operation, it would be very fast, but I canβt think of any way to do it at the moment!
source share