Skip to content

Instantly share code, notes, and snippets.

@reinholdsson
Last active January 6, 2023 12:12
Show Gist options
  • Save reinholdsson/b9fae8ab151a374928aa to your computer and use it in GitHub Desktop.
Save reinholdsson/b9fae8ab151a374928aa to your computer and use it in GitHub Desktop.
dplyr helper functions
#' Grouped mutate
#'
#' Group by columns, then mutate, and then regroup to previous groups.
#' @param .data data frame
#' @param .by character vector with columns to group by
#' @param ... arguments passed to mutate(...)
#' @export
grouped_mutate <- function(.data, .by, ...) {
pre <- groups(.data)
if (is.null(pre)) pre <- list()
regroup(.data, lapply(.by, as.symbol)) %>% mutate(...) %>% regroup(pre)
}
#' Relative difference between dates
#'
#' ...
#'
#' @param date_col date column
#' @param value_col value column
#' @param date_diff date difference, e.g. lubridate::days(7)
#'
#' @export
relative_by_date <- function(date_col, value_col, date_diff = lubridate::days(7)) {
sapply(as.Date(date_col), function(i){
p0 <- value_col[which(date_col == i - date_diff)]
p1 <- value_col[which(date_col == i)]
x <- (p1 - p0) / p0
if (length(x) != 0) x else NA
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment