Reputation: 7147
I am trying to calculate a rolling error function in R where I take the last 30 days and compute the rmse, move forward 1 day and take the last 30 days from this point and compute the new rmse.
My data looks like the following where I have a date and two values:
dates val1 val2
1 2010-01-01 -0.479526441 -0.294149127
2 2010-01-02 -0.860588950 0.426375720
3 2010-01-03 -0.660643894 -1.483020861
4 2010-01-04 -0.938748812 -1.631823690
Where am I going wrong in the code?
Data & attempt:
d <- data.frame(
dates = seq(from = as.Date("2010-01-01"), to = as.Date("2012-12-31"), by = 1),
val1 = rnorm(1096),
val2 = rnorm(1096)
)
d %>%
mutate(rollRMSE = rollapply(., width = 30, by = 1, FUN = Metrics::rmse(val1, val2)))
Upvotes: 0
Views: 849
Reputation: 1763
EDIT : setting window
size as a variable
I have sliced the steps, rollapply will result in 29 less data with a 30 window so may want to collect this in another tibble.
suppressPackageStartupMessages(library(dplyr))
d <- data.frame(
dates = seq(from = as.Date("2010-01-01"), to = as.Date("2012-12-31"), by = 1),
val1 = rnorm(1096),
val2 = rnorm(1096)
)
rse <- function(x, y){sqrt((x-y)**2)}
# assign window size for moving average
window <- 30
d %>% tibble::as_tibble() %>%
mutate(err = rse(val1, val2),
roll = c(zoo::rollapply(err, width = window, by = 1, FUN = mean), rep(NA, window -1) )
)
#> # A tibble: 1,096 x 5
#> dates val1 val2 err roll
#> <date> <dbl> <dbl> <dbl> <dbl>
#> 1 2010-01-01 -0.0248 1.18 1.20 1.40
#> 2 2010-01-02 -0.684 0.603 1.29 1.38
#> 3 2010-01-03 -0.344 -1.92 1.58 1.42
#> 4 2010-01-04 0.447 0.319 0.128 1.38
#> 5 2010-01-05 0.123 -0.810 0.933 1.42
#> 6 2010-01-06 0.00384 2.29 2.29 1.43
#> 7 2010-01-07 -1.51 -1.03 0.487 1.39
#> 8 2010-01-08 0.394 -1.25 1.64 1.41
#> 9 2010-01-09 -1.30 1.61 2.92 1.42
#> 10 2010-01-10 0.394 0.117 0.278 1.33
#> # ... with 1,086 more rows
Upvotes: 1
Reputation: 51622
You can do it manually with base R, i.e.
sapply(seq(0, (nrow(d) - 30)), function(i) Metrics::rmse(d$val1[(seq(30) + i)], d$val2[(seq(30) + i)]))
Upvotes: 1