Skip to content

Instantly share code, notes, and snippets.

@tonyelhabr
Last active February 13, 2020 17:17
Show Gist options
  • Save tonyelhabr/248ee6f152bcca2119cfd03bd95b1b9b to your computer and use it in GitHub Desktop.
Save tonyelhabr/248ee6f152bcca2119cfd03bd95b1b9b to your computer and use it in GitHub Desktop.
`expand.grid()` for years and months
library(tidyverse)
# grid_ym ----
.years <- 2017:2018
.months <- 1:12
grid_ym <-
crossing(
year = .years,
month = .months
) %>%
as_tibble() %>%
mutate_all(as.integer)
# Or...
grid_ym <-
tibble(
year = rep(.years, each = length(.months)),
month = rep(.months, each = length(.years))
) %>%
mutate_all(as.integer)
# grid_ymd_hm ----
.date1 <- '2017-01-01'
.date2 <- '2018-12-31'
seq_days <- seq.Date(as.Date(.date1), as.Date(.date2), by = 'day')
grid_ymd <-
seq_days %>%
tibble(date = .) %>%
mutate_at(
vars(date),
list(
year = lubridate::year,
month = lubridate::month,
day = lubridate::day
)
) %>%
mutate_at(vars(-date), as.integer)
grid_ymd
grid_hm <-
crossing(
hour = seq(1, 24, by = 1),
minute = seq(5, 60, by = 5),
second = 0
) %>%
as_tibble() %>%
mutate_all(as.integer)
grid_hm
grid_ymd_hm <-
grid_ymd %>%
mutate(dummy = 1) %>%
inner_join(grid_hm %>% mutate(dummy = 1)) %>%
arrange(date, hour, minute, second)
grid_ymd_hm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment