I was using rollapply
for a calculation that takes the last value in the roll and divides it by the mean minus one, which works fine as you can try for yourself:
set.seed(123)
v <- xts(rnorm(5, 5, 1), Sys.Date()-5:1)
rollapplyr(v, width = 3, function(x) x[3, ] / mean(x) - 1)
[,1]
2019-01-12 NA
2019-01-13 NA
2019-01-14 0.24784729
2019-01-15 -0.07241364
2019-01-16 -0.08178780
Then, I also needed to run the function with another parameter, eg. width = 4
. Of cause, the function needs to be adjusted too:
rollapplyr(v, width = 4, function(x) x[4, ] / mean(x) - 1)
[,1]
2019-01-12 NA
2019-01-13 NA
2019-01-14 NA
2019-01-15 -0.02670674
2019-01-16 -0.04696956
To be more flexible, I tried passing the width parameter directly into the function and got a result I did not expect, although the fourth column is correct:
rollapplyr(v, width = 4, function(x, width) x[width, ] / mean(x) - 1)
[,1] [,2] [,3] [,4]
2019-01-12 NA NA NA NA
2019-01-13 NA NA NA NA
2019-01-14 NA NA NA NA
2019-01-15 -0.1478253 -0.08442393 0.25895593 -0.02670674
2019-01-16 -0.1137588 0.21861923 -0.05789086 -0.04696956
Would anyone understand what is conceptually wrong with using the width parameter in FUN and how can the output be explained? Anyone has an idea how to do it right?