Reputation: 8425
Is it possible to use negative weights in the R
package RcppRoll
?
For example, say we have a series dd
and we wish to find a series of first differences:
library(RcppRoll)
set.seed(1)
dd <- 1:100 + runif(100)
So we know that dd[100] - dd[99]
is 0.79
... the other way of writing this is, of course, (-1L) * dd[99] + (1L) * dd[100]
.
The second way has the advantage of making the weights obvious. So, a weighted sum with weights c(-1L, 1L)
should return the series of differences; at least that's seems like correct math / logic.
diff_dd <- roll_sum(dd, n=2, weights = c(-1,1), align='right')
... we find that it is all NaN ...
tail(diff_dd)
[1] NaN NaN NaN NaN NaN NaN
what's going on?
Upvotes: 0
Views: 151
Reputation: 6151
The problem is the normalize
argument which is default set to TRUE
. The weights are normalized and since 1 + -1 = 0 things go haywire since the weights used are c(-1, 1)/0
. Try this and you should get what you want.
> diff_dd <- roll_sum(dd, n=2, weights = c(-1,1), align='right', normalize=FALSE)
> diff_dd
[1] 1.1066152 1.2007295 1.3353544 0.2934741 1.6967078 1.0462856 0.7161225 0.9683163 0.4326722 1.1441883
[11] 0.9705822 1.5104661 0.6970809 1.3857377 0.7278578 1.2199193 1.2742876 0.3881291 1.3974100 1.1572600
[21] 0.2774373 1.4395312 0.4738813 1.1416656 1.1188934 0.6272762 1.3689976 1.4873029 0.4706582 1.1417311
[31] 1.1174857 0.8939755 0.6926763 1.6411557 0.8410934 1.1257731 0.3137038 1.6157673 0.6875635 1.4096719
[41] 0.8261139 1.1358726 0.7701035 0.9766833 1.2596367 0.2339750 1.4538989 1.2550837 0.9604178 0.7848881
[51] 1.3835899 0.5768876 0.8067002 0.8258818 1.0287871 1.2168055 1.2023626 1.1433708 0.7448251 1.5060457
[61] 0.3807274 1.1654624 0.8733289 1.3184758 0.6071463 1.2205285 1.2877654 0.3179362 1.7910744 0.4637516
[71] 1.5003674 0.5072431 0.9870914 1.1425763 1.4158471 0.9721411 0.5256501 1.3873312 1.1832973 0.4740415
[81] 1.2778552 0.6874797 0.9253578 1.4317350 0.4456051 1.5084290 0.4105707 1.1237966 0.8978159 1.0963250
[91] 0.8193050 1.5833539 1.2339810 0.9026455 1.0183941 0.6579656 0.9548096 1.4007862 0.7940630
Upvotes: 1