Common functions used in functional programming. These are similar to their
respective counterparts in Base R: Map
, Reduce
,
Filter
, etc. However, they take any value that can be converted
to a function via lambda
and the function comes after the argument
in the argument list for convenience while piping.
map(
x,
f,
...,
simplify = FALSE,
USE.NAMES = FALSE,
FUN.VALUE = NULL,
clust = NULL
)mapn(
f,
...,
simplify = FALSE,
USE.NAMES = FALSE,
FUN.VALUE = NULL,
clust = NULL
)
ffind(x, f, ...)
filter(x, f, ...)
reduce(x, f, init = NULL, right = FALSE)
accumulate(x, f, init, right = FALSE)
compose(...)
vector
function to be applied to x
additional arguments supplied to f
, or a list of functions for compose
(applied in the order provided)
logical; should the results be simplified to an array?
logical; should x
be used as names for the result?
template vector for the return type
cluster to use for parallel
computations. See comprehension
for more details. FUN.VALUE
is ignored if a cluster is supplied.
object used to initialize reduce
, if an object other then the first value is desired
logical; should the reduction start from left (default) or right?
determined by the return value of the function f
.
map
: Apply function f
using elements in vector x
at each index.
mapn
: Apply function f
using the element in all elements in vectors ...
at each index as arguments.
ffind
: Find the position of elements in vector x
that satisfy predicate function f
.
filter
: Extract elements in vector x
that satisfy predicate function f
.
reduce
: Combine elements in a vector x
using binary function f
.
accumulate
: Combine elements in a vector x
using binary function f
, accumulating the results.
compose
: Combine functions into a single function.
map
is slightly different from Map
in Base R other than
the argument order. First, iter
is applied to the vector x
so that users can define behavior for custom classes. Second, lambda
is applied to f
. map
only works for a single vector. Use mapn
to use multiple vectors as the function argument. The map
functions are
wrappers around sapply
or link[base]{vapply}
(if FUN.VALUE
is provided).
The other functions behave similar to what one would expect, with the exception
of accumulate
. accumulate
does not produce all intermediate results;
it only provides the final cumulative vector.
compose
takes multiple functions and produces a single "composed" function.
When the composed function is called, each function in the list is applied sequentially
to the arguments. The functions can be retrieved from the composed function's
attributes.
# NOT RUN {
x <- list(1:3, 4:6, 7:9)
map(x, ~Reduce(`-`, .i))
map(x, sqrt)
filter(x[[1]], ~.i < 3)
reduce(x[[3]], `*`, init=1)
f <- compose(sqrt, log, `*`(2))
f(10)
# }
Run the code above in your browser using DataLab