Skip to content

Instantly share code, notes, and snippets.

View DavisVaughan's full-sized avatar

Davis Vaughan DavisVaughan

View GitHub Profile
library(tidyverse)
library(almanac)
library(clock)
# Define a recurrence rule for "all weekdays"
on_weekdays <- daily(since = "2012-01-01", until = "2022-12-31") %>%
recur_on_weekdays()
# Generate all of the "events" in the recurrence rule (i.e. all weekdays)
# then manipulate the results to get the day number per month
df <- tibble(
g = c(1, 1, 1, 1, 2, 2, 2, 2),
x = 1:8,
y = 8:1
)
# Group to show that this is applied per groups nicely
df <- group_by(df, g)
x <- df$x
library(lubridate)
x <- years(1)
y <- years(3)
# difftime doesn't work with period objects
difftime(x, y)
#> Error in as.POSIXct.numeric(time1): 'origin' must be supplied
# you can just ignore this Note
library(slider)
library(dplyr)
library(lubridate)
df <- tibble(
x = c(.5, .8, .7, .5, .2, .06, 0, 0, 0, 0, 0, .1, .3, .2, 0),
date = as.Date("2005-07-20") + 0:14
)
# Check that the window made up of "the current day plus 4 days before it" are all >0
@DavisVaughan
DavisVaughan / flexible-joins.R
Last active June 25, 2021 14:02
flexible-joins
library(dplyr)
x <- tibble(
a1 = c(1, 5, 7, 12),
a2 = c(4, 6, 11, 15)
)
y <- tibble(
b = c(2, 3, 1, 4, 6, 0, 14)
)
library(clock)
library(almanac)
library(tidyr)
# All possible Monday/Friday pairs in 2019
# (note some will be invalid, which will need to be removed)
grid <- expand_grid(
year = 2019,
month = 1:12,
day = c(clock_weekdays$monday, clock_weekdays$friday),