# runner returns windows as is by default
runner(1:10)
# mean on k = 3 elements windows
runner(1:10, f = mean, k = 3)
# mean on k = 3 elements windows with different specification
runner(1:10, k = 3, f = function(x) mean(x, na.rm = TRUE))
# concatenate two columns
runner(
data.frame(
a = letters[1:10],
b = 1:10
),
f = function(x) paste(paste0(x$a, x$b), collapse = "+")
)
# concatenate two columns with additional argument
runner(
data.frame(
a = letters[1:10],
b = 1:10
),
f = function(x, xxx) {
paste(paste0(x$a, xxx, x$b), collapse = " + ")
},
xxx = "..."
)
# number of unique values in each window (varying window size)
runner(letters[1:10],
k = c(1, 2, 2, 4, 5, 5, 5, 5, 5, 5),
f = function(x) length(unique(x))
)
# concatenate only on selected windows index
runner(letters[1:10],
f = function(x) paste(x, collapse = "-"),
at = c(1, 5, 8)
)
# 5 days mean
idx <- c(4, 6, 7, 13, 17, 18, 18, 21, 27, 31, 37, 42, 44, 47, 48)
runner::runner(
x = idx,
k = "5 days",
lag = 1,
idx = Sys.Date() + idx,
f = function(x) mean(x)
)
# 5 days mean at 4-indices
runner::runner(
x = 1:15,
k = 5,
lag = 1,
idx = idx,
at = c(18, 27, 48, 31),
f = mean
)
# runner with data.frame
df <- data.frame(
a = 1:13,
b = 1:13 + rnorm(13, sd = 5),
idx = seq(as.Date("2022-02-22"), as.Date("2023-02-22"), by = "1 month")
)
runner(
x = df,
idx = "idx",
at = "6 months",
f = function(x) {
cor(x$a, x$b)
}
)
# parallel computing
library(parallel)
data <- data.frame(
a = runif(100),
b = runif(100),
idx = cumsum(sample(rpois(100, 5)))
)
const <- 0
cl <- makeCluster(1)
clusterExport(cl, "const", envir = environment())
runner(
x = data,
k = 10,
f = function(x) {
cor(x$a, x$b) + const
},
idx = "idx",
cl = cl
)
stopCluster(cl)
# runner with matrix
data <- matrix(data = runif(100, 0, 1), nrow = 20, ncol = 5)
runner(
x = data,
f = function(x) {
tryCatch(
cor(x),
error = function(e) NA
)
}
)
Run the code above in your browser using DataLab