[R] "Fold" in R?

Gabor Grothendieck ggrothendieck at myway.com
Sun Mar 27 19:46:23 CEST 2005


Seung Jun <jun <at> cc.gatech.edu> writes:

: 
: Fold in Mathematica (or reduce in Python) works as follows:
: 
: Fold[f, x, {a, b, c}] := f[f[f[x,a],b],c]
: 
: That is, f is a binary operator, x is the initial value, and the results 
: are cascaded along the list.  I've found it useful for reducing lists 
: when I only have a function that accepts two arguments (e.g., merge in R).
: 
: Is there any R equivalent?  I'm a newbie in R and having a hard time 
: finding such one.  Thank you.
: 

You could define it yourself like this:

   Fold <- function(f, x, L) for(e in L) x <- f(x, e)

   # example of its use
   result <- Fold(sum, 0, 1:3)  # result is 6


Note that merge.zoo in the zoo package does handle multiple
arguments; however, that is intended for merging time series
along their times, in case that is your application.




More information about the R-help mailing list