slider 行

library(slider)
library(lubridate)
library(tidyverse)

x <- c(1, 2, 3, 4, 5)

# .before: How many elements before the current one should be included in the window?
# .after: How many elements after the current one should be included in the window?
# .complete: Should .f only be evaluated when there is enough data to make a complete window?ff
# .step: The number of elements to shift forward between calls to .f.
slide_vec(x, mean, .before = 1)
slide_vec(x, mean, .after = 1)
slide_vec(x, sum, .before = 2)
slide_vec(x, sum, .before = 2, .complete = T)

index_vec <- as.Date("2019-08-29") + c(0, 1, 5, 6)
wday_vec <- as.character(wday(index_vec, label = TRUE))
sales_vec <- c(2, 4, 3, 5)

company <- tibble(sales = sales_vec,
                  index = index_vec,
                  wday = wday_vec)

# Over columns:
map(company, ~ .x)

# Over rows:
#
slide(company, ~ .x)


big_index_vec <- c(as.Date("2019-08-30") + 0:4,
                   as.Date("2019-11-30") + 0:4)

big_sales_vec <- c(2, 4, 6, 2, 8, 10, 9, 3, 5, 2)

big_company <- tibble(sales = big_sales_vec,
                      index = big_index_vec)

big_company

slide_period(big_company, big_company$index, "month", ~ .x)

monthly_summary <- function(data) {
  summarise(
    data,
    start = min(index),
    end = max(index),
    total_sales = sum(sales)
  )
}

slide_period_dfr(big_company,
                 big_company$index,
                 "month",
                 monthly_summary)

#等价于
big_company %>%
  mutate(monthly = floor_date(index, "month")) %>%
  group_by(monthly) %>%
  summarise(sales = sum(sales))

slide_period_dfr(big_company,
                 big_company$index,
                 "month",
                 monthly_summary,
                 .before = 1)

评论

此博客中的热门博文

V2ray websocket(ws)+tls+nginx分流

Rstudio 使用代理