optimized rolling functions on irregular time series with time-based window

前端 未结 5 820
情深已故
情深已故 2020-12-01 09:42

Is there some way to use rollapply (from zoo package or something similar) optimized functions (rollmean, rollmedian etc) to compute r

5条回答
  •  温柔的废话
    2020-12-01 09:46

    Most of the answers suggest to insert NA to make the time series regular. However, this can be slow in case of long time series. Additionally, it does not work for functions which can not be used with NA.

    The width argument of rollapply (zoo package) can be a list (see help of rollapply for details). Based on this I wrote a function which creates a list to be used with rollapply as width parameter. The function extracts indexes for irregular zoo objects if the moving window is to be time and not index based. Therefore the index of the zoo object should be the actual time.

    # Create a zoo object where index represents time (e.g. in seconds) 
    
    d <- zoo(c(1,1,1,1,1,2,2,2,2,2,16,25,27,27,27,27,27,31),     
             c(1:5,11:15,16,25:30,31))
    
    # Create function 
    
    createRollapplyWidth = function(zoodata, steps, window ){   
    
      mintime =  min(time(zoodata))     
    
      maxtime =  max(time(zoodata)) 
    
      spotstime = seq(from = mintime , to = maxtime, by = steps)
    
      spotsindex = list() 
    
        for (i in 1:length(spotstime)){
        spotsindex[[i]] =  as.numeric(which(spotstime[i]  <=  time(zoodata) & time(zoodata) < spotstime[i] + window))}
    
      rollapplywidth = list()
        for (i in 1:length(spotsindex)){
        if (!is.na(median(spotsindex[[i]])) ){ 
          rollapplywidth[[round(median(spotsindex[[i]]))]] = spotsindex[[i]] - round(median(spotsindex[[i]]))}
      }
      return(rollapplywidth)
      }
    
    
    # Create width parameter for rollapply using function
    
    rollwidth =  createRollapplyWidth(zoodata = d, steps = 5, window = 5) 
    
    # Use parameter in rollapply 
    
    result = rollapply(d, width = rollwidth , FUN =  sum, na.rm = T) 
    result
    

    Limitation: not based on dated but on time in seconds. Parameter "partial" of rollapply does not work.

提交回复
热议问题