Functional Programming Patterns
Predicate Filter
Keep Matching Values
A predicate is a function that returns TRUE or FALSE for each input value.
Program
Play the script to change the minimum value used by the predicate.
predicate_filter.R
min_value <-
values <- c(1, 3, 5, 7)
keep <- function(x) x >= min_value
selected <- values[vapply(values, keep, logical(1))]
count <- length(selected)
label <- paste("count", count, sep = ":")
cat(label, "\n", sep = "")
min_value <-
values <- c(1, 3, 5, 7)
keep <- function(x) x >= min_value
selected <- values[vapply(values, keep, logical(1))]
count <- length(selected)
label <- paste("count", count, sep = ":")
cat(label, "\n", sep = "")
min_value <-
values <- c(1, 3, 5, 7)
keep <- function(x) x >= min_value
selected <- values[vapply(values, keep, logical(1))]
count <- length(selected)
label <- paste("count", count, sep = ":")
cat(label, "\n", sep = "")
predicate
The `keep` function returns one logical value for each input.
logical map
`vapply(values, keep, logical(1))` evaluates the predicate across the vector.
filter
Indexing with the logical result keeps only matching values.