rlistvectortime-seriesmoving-average

Using runner::runner to extract sliding windows from timeseries


I want to calculate a parameter (not with a standard function like mean()) for sliding windows. I have found the runner::runner() function, which is probably capable of providing the functionality that I want, i.e. sliding windows based on time, robust in case of missing dates and uneven spacing, but I cannot get the right syntax.

Please see my reprex below, where I try to get windows of three days in length with a lag of 1 day. So window_nr1 would be: d0 - d3, window_nr2: d1 - d4 etc.:

Data:
library(runner)
t <- seq(from=0, to=(3600*24*5), by=3600)
runner(x=t, k=(3600*24*3), lag=(3600*24), idx=t)

Expected output:

[[1]]
[1] 0 ...... [72] 259200
...
[[3]]
[1] 172800 .... [72] 432000
...
## --> one window spans three days, with one day overlap

Instead I get this:

[[96]]
[1] 0 ..... [72] 255600
[[97]]
[1] 3600 ... [72] 259200
[[98]]
[1] 7200 .... [72] 262800
...
## --> basically no matter what I enter for lag, 
##     the window shifts one hour (3600s), or one step along `t`.

I have one major and one minor question:


Solution

  • You need at instead of lag; we can also use Filter() to filter out elements that are less than 3 days long.

    To make this easier to comprehend, I used hours instead of seconds, but you can simply multiply the output by 3600.

    library(runner)
    t <- seq(from=0, to=(24*5), by=1)
    
    Filter(\(v) length(v) == (24*3), 
           runner(x=t, k=(24*3), at = seq(0, 24*5, by = 24))) -> OUTPUT
    
    OUTPUT
    
    #> [[1]]
    #>  [1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
    #> [26] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    #> [51] 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    #> 
    #> [[2]]
    #>  [1] 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    #> [26] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    #> [51] 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    #> 
    #> [[3]]
    #>  [1]  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66
    #> [20]  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85
    #> [39]  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104
    #> [58] 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    
    ## to get the desired output in seconds 
    # OUTPUT * 3600
    

    Created on 2025-04-03 with reprex v2.1.1