-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpand_month.R
40 lines (35 loc) · 1.01 KB
/
expand_month.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#' Expand month
#'
#' @param df dataframe to create monthly avg series
#'
#' @return a monthly average of the initial df
#' @export
expand_month <- function(df) {
daily <- df %>%
rowwise() %>%
mutate(
date_start = as.Date(date) - 6,
) %>%
relocate(date_start, .after = date) %>%
do(
data.frame(.[1:2], daily = seq(.$date_start, .$date, by = "1 day"))
) %>%
left_join(df, by = "date")
avg <- daily %>%
rowwise() %>%
mutate(
year = year(daily),
month = month(daily),
date_day = lubridate::days_in_month(as.Date(
paste(year, month, "01", sep = "-"), "%Y-%m-%d")),
date_monthly = as.Date(
paste(year, month, date_day, sep = "-"), "%Y-%m-%d")
) %>%
select(-c(date, date_start, date_day, year, month)) %>%
group_by(date_monthly) %>%
summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE)))
month <- avg %>%
rename_all(list(~ (paste0(make.names(names(df)), "m")))) %>%
rename("date" = "datem")
return(month)
}