简体   繁体   中英

Do not understand what rollapply is doing

z <- zoo::zoo(1:5, as.Date(0:4))
z
1970-01-01 1970-01-02 1970-01-03 1970-01-04 1970-01-05 
         1          2          3          4          5 

Then tried:

rollapply(z, 1:2, sum, align = "left")
1970-01-01 1970-01-02 1970-01-03 1970-01-04 1970-01-05 
         1          5          3          9          5 

I'm not seeing the connection between z and the rollapply() function call. My assumption was that I would have a vector, two long (1:2) that would overlay on each observation within z and agggregate by my function sum.

The first number in z is 1 and the first in my call is also 1. OK makes sense, the sum of 1 and nothing is just 1.

The second instance in z is 2 and the second result in rollapply is 5. I can see that the sum of the 2nd and 3rd entries in z are 5 but if that was whats going on then woulndn't the 3rd result of rollapply be 3 + 4 = 7 instead of 3. How did my rollapply call return 3 for the 3rd case?

What is r doing here exactly?

The window is alternating between a width of 1 and a width of 2. The results are 1, then 2 + 3, then 3, then 4 + 5, then 5.

Here is the rollapply output with a window width of 1 (column 1) and with a window width of 2 (column 2). You can see that it just alternates between these two.

sapply(1:2, function(w) rollapply(z, w, sum, align = 'left', fill = NA))
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    5
# [3,]    3    7
# [4,]    4    9
# [5,]    5   NA

If you want both, and want to preserve the attributes, you can use lapply

lapply(1:2, function(w) rollapply(z, w, sum, align = 'left', fill = NA))

# [[1]]
# 1970-01-01 1970-01-02 1970-01-03 1970-01-04 1970-01-05 
#          1          2          3          4          5 
# 
# [[2]]
# 1970-01-01 1970-01-02 1970-01-03 1970-01-04 1970-01-05 
#          3          5          7          9         NA

The same thing happens if you supply a larger vector as the second argument to rollapply

rollapply(1:10, 2:4, sum)
# [1]  3  6 14  9 15 26 15 24
sapply(2:4, function(w) rollapply(1:10, w, sum, fill = NA))
#       [,1] [,2] [,3]
#  [1,]    3   NA   NA
#  [2,]    5    6   10
#  [3,]    7    9   14
#  [4,]    9   12   18
#  [5,]   11   15   22
#  [6,]   13   18   26
#  [7,]   15   21   30
#  [8,]   17   24   34
#  [9,]   19   27   NA
# [10,]   NA   NA   NA

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