slide() is an S3 method to carry out rolling window calculation; slider() splits the input x to a list according to the window size.

slide(x, .f, ..., size = 1, fill)

# S3 method for default
slide(x, .f, ..., size = 1, fill = NA_real_)

# S3 method for data.frame
slide(x, .f, ..., size = 1, fill = NA,
  deframe = TRUE)

slider(x, size = 1)

Arguments

x

A vector of numerics, or data frame.

.f

A function or one-sided formula using purrr-like syntax. If a formula, it is converted to a function.

...

Additional arguments passed on to .f.

size

An integer for window size.

fill

A single value or data frame to replace NA.

deframe

TRUE a list is returned. FALSE returns a data frame.

Details

The slide() function attempts to tackle more general problems using the purrr-like syntax. For some specialist functions like mean and sum, you may like to check out for RcppRoll for faster performance.

See also

tile for tiling window without overlapping observations; stretch for expanding more observations

Examples

# sliding through a vector ---- x <- 1:10 slide(x, mean, size = 3)
#> [1] NA NA 2 3 4 5 6 7 8 9
slide(x, ~ mean(.), size = 3)
#> [1] NA NA 2 3 4 5 6 7 8 9
slide(x, mean, size = 3, fill = 0)
#> [1] 0 0 2 3 4 5 6 7 8 9
# slider ---- slider(x, size = 3)
#> [[1]] #> [1] 1 2 3 #> #> [[2]] #> [1] 2 3 4 #> #> [[3]] #> [1] 3 4 5 #> #> [[4]] #> [1] 4 5 6 #> #> [[5]] #> [1] 5 6 7 #> #> [[6]] #> [1] 6 7 8 #> #> [[7]] #> [1] 7 8 9 #> #> [[8]] #> [1] 8 9 10 #>
# NOT RUN { # takes a little longer for cran check # sliding a 2-day window for a data frame ---- sx <- pedestrian %>% filter(Sensor == "Southern Cross Station", Date <= as.Date("2015-01-31")) # directly return a data frame of fitted values and residuals diag_sx <- sx %>% slide(function(x) { fit <- lm(Count ~ Time, data = x) data.frame(fitted = fitted(fit), resid = residuals(fit)) }, size = 48, deframe = FALSE) diag_sx[48:57, ] # save lm models as additional columns lm_sx <- sx %>% mutate(lm = slide(., ~ lm(Count ~ Time, data = .), size = 48)) lm_sx[48:57, ] # }