#' filter for
#'
#' Filter for all instances of a column that meet a specific condition at least once.
#'
#' @param .data data frame
#' @param what unquote col or vector of unquoted cols.
#' @param where a logical condition used for filter
#'
#' @return data frame
#' @export
#'
#' @examples
#'
#' # An example using some time series data
#' tibble::tibble( CLIENT_ID = c("A1001", "B1001", "C1001",
#' "A1001", "B1001", "C1001", "A1001", "B1001", "C1001"),
#' YEAR = c(2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 2021L, 2021L, 2021L),
#' SALES = c(3124, 56424, 3214132, 65534, 2342, 6566, 87654, 2332, 6565)
#' ) %>%
#' dplyr::arrange(CLIENT_ID, YEAR) -> sales_data
#'
#' sales_data
#'
#' # filter for Clients that had sales greater than 4000 in the year 2019.
#' # this way we can see how the same clients sales looked in subsequent years
#'
#' sales_data %>%
#' filter_for(what = CLIENT_ID, where = YEAR == 2019 & SALES > 4000L)
#'
#'
#' # filter for clients whose sales were less than 4000 in the year 2021
#' sales_data %>%
#' filter_for(what = CLIENT_ID, where = YEAR == 2021 & SALES < 4000L)
filter_for <- function(.data, what, where){
wheres <- rlang::enexpr(where)
whats <- rlang::enexpr(what)
.data %>%
dplyr::filter(!!wheres) %>%
dplyr::distinct(dplyr::across(!!whats)) -> whats1
suppressMessages({
.data %>%
dplyr::inner_join(whats1)
})
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.