library(timeplyr)
# \dontshow{
.n_dt_threads <- data.table::getDTthreads()
.n_collapse_threads <- collapse::get_collapse()$nthreads
data.table::setDTthreads(threads = 1L)
collapse::set_collapse(nthreads = 1L)
# }
x <- 1:10
roll_sum(x) # Simple rolling total
roll_mean(x) # Simple moving average
roll_sum(x, window = 3)
roll_mean(x, window = 3)
roll_sum(x, window = 3, partial = FALSE)
roll_mean(x, window = 3, partial = FALSE)
# Plot of expected value of 'coin toss' over many flips
set.seed(42)
x <- sample(c(1, 0), 10^3, replace = TRUE)
ev <- roll_mean(x)
plot(ev)
abline(h = 0.5, lty = 2)
all.equal(roll_sum(iris$Sepal.Length, g = iris$Species),
ave(iris$Sepal.Length, iris$Species, FUN = cumsum))
# The below is run using parallel computations where applicable
roll_sum(iris[, 1:4], window = 7, g = iris$Species)
# \donttest{
library(data.table)
library(bench)
df <- data.table(g = sample.int(10^4, 10^5, TRUE),
x = rnorm(10^5))
mark(e1 = df[, mean := frollmean(x, n = 7,
align = "right", na.rm = FALSE), by = "g"]$mean,
e2 = df[, mean := roll_mean(x, window = 7, g = get("g"),
partial = FALSE, na.rm = FALSE)]$mean)
# }
# \dontshow{
data.table::setDTthreads(threads = .n_dt_threads)
collapse::set_collapse(nthreads = .n_collapse_threads)
# }
Run the code above in your browser using DataLab