Learn R Programming

tsibble (version 0.2.0)

slide: Sliding window calculation

Description

Rolling window with overlapping observations:

  • slide() always returns a vector of numerics

  • slide_lst() returns a list

  • slide_dfr() return data frame using row-binding

  • slider() splits the input x to a list according to the window size.

Usage

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

slide_lst(x, .f, ..., size = 1, fill = NA)

slide_dfr(x, .f, ..., size = 1, fill = NA, .id = NULL)

slider(x, size = 1)

Arguments

x

A vector of numerics, or data frame. If a data frame, row-wise rolling window is performed.

.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.

.id

If not NULL a variable with this name will be created giving either the name or the index of the data frame, which is passed to dplyr::bind_rows.

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 ----
jan <- pedestrian %>% 
  filter(Date <= as.Date("2015-01-31")) %>% 
  split_by(Sensor)
# returns a data frame of fitted values and residuals for each sensor,
# and then combines
diag_jan <- jan %>%
  purrr::map_dfr(
    ~ slide_dfr(., function(x) {
      fit <- lm(Count ~ Time, data = x)
      data.frame(fitted = fitted(fit), resid = residuals(fit))
    }, size = 48)
  )
diag_jan[48:57, ]
# save lm models as additional columns
lm_jan <- jan %>% 
  purrr::map(
    ~ mutate(., lm = slide_lst(., ~ lm(Count ~ Time, data = .), size = 48)
  ))
lm_jan[[1]][48:57, ]
# }

Run the code above in your browser using DataLab