#' Evaluate logical predicates for each element of the list
#'
#' @param .data a list.
#' @param \dots logical predicates defined in terms of the variables in
#' \code{.data}.
#'
#' @examples
#'
#' as_lol(mtcars) %>%
#' check_cond_and(cyl == 4, mpg > 30)
#'
#' as_lol(mtcars) %>%
#' check_cond_or(cyl == 4, mpg > 30)
#'
#' @export
check_cond_and <- function(.data, ...) UseMethod("check_cond_and")
#' @export
check_cond_and.list <- function(.data, ...) {
dots <- quos(...)
map_lgl(.data, function(.x) {
all(unlist(try_eval(dots, data = as.list(.x))))
})
}
#' @rdname check_cond_and
#' @export
check_cond_or <- function(.data, ...) UseMethod("check_cond_or")
#' @export
check_cond_or.list <- function(.data, ...) {
dots <- quos(...)
map_lgl(.data, function(.x) {
any(unlist(try_eval(dots, data = as.list(.x))))
})
}
#' Return entries with matching conditions
#'
#' \code{filter_and} joins conditions with logical AND,
#' while \code{filter_or} joins conditions with logical OR.
#' \code{filter} is a wrapper around \code{filter_and} function.
#'
#' @param .data a list.
#' @param \dots logical predicates defined in terms of the variables in
#' \code{.data}. Only entries where the condition evaluate to
#' \code{TRUE} are kept.
#'
#' @seealso \code{\link[dplyr]{filter}}, \code{\link{check_cond_and}}
#'
#' @examples
#'
#' as_lol(mtcars) %>%
#' filter(cyl == 4, mpg > 30) %>%
#' summarise(
#' cyl_range = range(cyl),
#' min_mpg = min(mpg)
#' )
#'
#' as_lov(mtcars) %>%
#' filter(mpg > 30)
#'
#' @export
filter_and <- function(.data, ...) UseMethod("filter_and")
#' @export
filter_and.list <- function(.data, ...) {
.data[check_cond_and(.data, ...)]
}
#' @rdname filter_and
#' @export
filter_or <- function(.data, ...) UseMethod("filter_or")
#' @export
filter_or.list <- function(.data, ...) {
.data[check_cond_or(.data, ...)]
}
#' @rdname filter_and
#' @export
filter.list <- function(.data, ...) {
filter_and(.data, ...)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.