Learn R Programming

tsibble (version 0.1.0)

slide: Sliding window calculation

Description

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

Usage

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

Run this code
# NOT RUN {
# sliding through a vector ----
x <- 1:10
slide(x, mean, size = 3)
slide(x, ~ mean(.), size = 3)
slide(x, mean, size = 3, fill = 0)

# slider ----
slider(x, size = 3)

# }
# 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, ]
# }

Run the code above in your browser using DataLab