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. Seung
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.Tried searching the mailing list for "Fold"? It was discussed on this very list in November. http://cran.r-project.org/search.html http://maths.newcastle.edu.au/~rking/R/ -- O__ ---- Peter Dalgaard Blegdamsvej 3 c/ /'_ --- Dept. of Biostatistics 2200 Cph. N (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
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.