| funprog | R Documentation |
Reduce uses a binary function to successively combine theelements of a given vector and a possibly given initial value.Filter extracts the elements of a vector for which a predicate(logical) function gives true.Find andPosition givethe first or last such element and its position in the vector,respectively.Map applies a function to the correspondingelements of given vectors.Negate creates the negation of agiven function.
Reduce(f, x, init, right = FALSE, accumulate = FALSE)Filter(f, x)Find(f, x, right = FALSE, nomatch = NULL)Map(f, ...)Negate(f)Position(f, x, right = FALSE, nomatch = NA_integer_)
f | a function of the appropriate arity (binary for |
x | a vector. |
init | anR object of the same kind as the elements of |
right | a logical indicating whether to proceed from left toright (default) or from right to left. |
accumulate | a logical indicating whether the successive reducecombinations should be accumulated. By default, only the finalcombination is used. |
nomatch | the value to be returned in the case when“no match” (no element satisfying the predicate) is found. |
... | vectors. |
Ifinit is given,Reduce logically adds it to the start(when proceeding left to right) or the end ofx, respectively.If this possibly augmented vectorv hasn > 1 elements,Reduce successively appliesf to the elements ofvfrom left to right or right to left, respectively. I.e., a leftreduce computesl_1 = f(v_1, v_2),l_2 = f(l_1, v_3), etc.,and returnsl_{n-1} = f(l_{n-2}, v_n), and a right reduce doesr_{n-1} = f(v_{n-1}, v_n),r_{n-2} = f(v_{n-2}, r_{n-1})and returnsr_1 = f(v_1, r_2). (E.g., ifv is thesequence (2, 3, 4) andf is division, left and right reduce give(2 / 3) / 4 = 1/6 and2 / (3 / 4) = 8/3, respectively.)Ifv has only a single element, this is returned; if there areno elements,NULL is returned. Thus, it is ensured thatf is always called with 2 arguments.
The current implementation is non-recursive to ensure stability andscalability.
Reduce is patterned after Common Lisp'sreduce. Areduce is also known as a fold (e.g., in Haskell) or an accumulate(e.g., in the C++ Standard Template Library). The accumulativeversion corresponds to Haskell's scan functions.
Filter applies the unary predicate functionf to eachelement ofx, coercing to logical if necessary, and returns thesubset ofx for which this gives true. Note that possibleNA values are currently always taken as false; control overNA handling may be added in the future.Filtercorresponds tofilter in Haskell orremove-if-not inCommon Lisp.
Find andPosition are patterned after Common Lisp'sfind-if andposition-if, respectively. If there is anelement for which the predicate function gives true, then the first orlast such element or its position is returned depending on whetherright is false (default) or true, respectively. If there is nosuch element, the value specified bynomatch is returned. Thecurrent implementation is not optimized for performance.
Map is a simple wrapper tomapply which does notattempt to simplify the result, similar to Common Lisp'smapcar(with arguments being recycled, however). Future versions may allowsome control of the result type.
Negate corresponds to Common Lisp'scomplement. Given a(predicate) functionf, it creates a function which returns thelogical negation of whatf returns.
FunctionclusterMap andmcmapply (notWindows) in packageparallel provide parallel versions ofMap.
## A general-purpose adder:add <- function(x) Reduce("+", x)add(list(1, 2, 3))## Like sum(), but can also used for adding matrices etc., as it will## use the appropriate '+' method in each reduction step.## More generally, many generics meant to work on arbitrarily many## arguments can be defined via reduction:FOO <- function(...) Reduce(FOO2, list(...))FOO2 <- function(x, y) UseMethod("FOO2")## FOO() methods can then be provided via FOO2() methods.## A general-purpose cumulative adder:cadd <- function(x) Reduce("+", x, accumulate = TRUE)cadd(seq_len(7))## A simple function to compute continued fractions:cfrac <- function(x) Reduce(function(u, v) u + 1 / v, x, right = TRUE)## Continued fraction approximation for pi:cfrac(c(3, 7, 15, 1, 292))## Continued fraction approximation for Euler's number (e):cfrac(c(2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8))## Iterative function application:Funcall <- function(f, ...) f(...)## Compute log(exp(acos(cos(0))))Reduce(Funcall, list(log, exp, acos, cos), 0, right = TRUE)## n-fold iterate of a function, functional style:Iterate <- function(f, n = 1) function(x) Reduce(Funcall, rep.int(list(f), n), x, right = TRUE)## Continued fraction approximation to the golden ratio:Iterate(function(x) 1 + 1 / x, 30)(1)## which is the same ascfrac(rep.int(1, 31))## Computing square root approximations for x as fixed points of the## function t |-> (t + x / t) / 2, as a function of the initial value:asqrt <- function(x, n) Iterate(function(t) (t + x / t) / 2, n)asqrt(2, 30)(10) # Starting from a positive value => +sqrt(2)asqrt(2, 30)(-1) # Starting from a negative value => -sqrt(2)## A list of all functions in the base environment:funs <- Filter(is.function, sapply(ls(baseenv()), get, baseenv()))## Functions in base with more than 10 arguments:names(Filter(function(f) length(formals(f)) > 10, funs))## Number of functions in base with a '...' argument:length(Filter(function(f) any(names(formals(f)) %in% "..."), funs))## Find all objects in the base environment which are *not* functions:Filter(Negate(is.function), sapply(ls(baseenv()), get, baseenv()))Add the following code to your website.
For more information on customizing the embed code, readEmbedding Snippets.