library(timeplyr)
library(lubridate)
library(dplyr)
library(fastplyr)
# \dontshow{
.n_dt_threads <- data.table::getDTthreads()
.n_collapse_threads <- collapse::get_collapse()$nthreads
data.table::setDTthreads(threads = 1L)
collapse::set_collapse(nthreads = 1L)
# }
time <- time_seq(today(), today() + weeks(3), "3 days")
set.seed(99)
x <- sample.int(length(time))
roll_mean(x, window = 7)
roll_sum(x, window = 7)
time_roll_mean(x, window = days(7), time = time)
time_roll_sum(x, window = days(7), time = time)
# Alternatively and more verbosely
x_chunks <- time_roll_window(x, window = 7, time = time)
x_chunks
vapply(x_chunks, mean, 0)
# Interval (x - 3 x]
time_roll_sum(x, window = days(3), time = time)
# An example with an irregular time series
t <- today() + days(sort(sample(1:30, 20, TRUE)))
time_elapsed(t, days(1)) # See the irregular elapsed time
x <- rpois(length(t), 10)
new_tbl(x, t) %>%
mutate(sum = time_roll_sum(x, time = t, window = days(3))) %>%
time_ggplot(t, sum)
# \donttest{
### Rolling mean example with many time series
# Sparse time with duplicates
index <- sort(sample(seq(now(), now() + dyears(3), by = "333 hours"),
250, TRUE))
x <- matrix(rnorm(length(index) * 10^3),
ncol = 10^3, nrow = length(index),
byrow = FALSE)
zoo_ts <- zoo::zoo(x, order.by = index)
# Normally you might attempt something like this
apply(x, 2,
function(x){
time_roll_mean(x, window = dmonths(1), time = index)
}
)
# Unfortunately this is too slow and inefficient
# Instead we can pivot it longer and code each series as a separate group
tbl <- ts_as_tbl(zoo_ts)
tbl %>%
mutate(monthly_mean = time_roll_mean(value, window = dmonths(1),
time = time, g = group))
# }
# \dontshow{
data.table::setDTthreads(threads = .n_dt_threads)
collapse::set_collapse(nthreads = .n_collapse_threads)
# }
Run the code above in your browser using DataLab