Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the FoldLeft function available in R?

I would like to know if there is an implementation of the foldLeft function (and foldRight?) in R.

The language is supposed to be "rather" functional oriented and hence I think there should be something like this, but I could not find it in the documentation.

To me, foldLeft function applies on a list and has the following signature:

foldLeft[B](z : B)(f : (B, A) => B) : B

It is supposed to return the following result:

f(... (f(f(z, a0), a1) ...), an) if the list is [a0, a1, ..., an].

(I use the definition of the Scala List API)

Does anybody know if such a function exists in R?

like image 962
SRKX Avatar asked Jun 15 '10 04:06

SRKX


People also ask

What does scala foldLeft do?

foldLeft() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It navigates elements from Left to Right order. It is primarily used in recursive functions and prevents stack overflow exceptions.

What does fold function do?

In functional programming, fold (also termed reduce, accumulate, aggregate, compress, or inject) refers to a family of higher-order functions that analyze a recursive data structure and through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a ...

What is fold in scheme?

Folding (also known as reduce or accumulate) is a method of reducing a sequence of terms down to a single term. This is accomplished by providing a fold function with a binary operator, an initial (or identity) value, and a sequence. There are two kinds of fold: a right one and a left one.


2 Answers

?Reduce. Usage Reduce(f, x, init, right = FALSE, accumulate = FALSE)

like image 101
ahala Avatar answered Sep 29 '22 04:09

ahala


If you want a vector of results, this will work:

foldl = function(f, v, x) {w = v; for (i in 1 : length(v)) { x = w[[i]] = f(x, v[[i]]) }; w }

Now you can redefine cumsum as

cumsum(v) = foldl(function(x,y) { x+y }, v, 0)

To improve it you should handle missing values like Reduce does.

like image 43
reinierpost Avatar answered Sep 29 '22 02:09

reinierpost