Re: [R] "Fold" in R?

From: Gabor Grothendieck <>
Date: Mon 28 Mar 2005 - 03:46:23 EST

Seung Jun <jun <at>> 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. mailing list PLEASE do read the posting guide! Received on Mon Mar 28 03:53:37 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:56 EST