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?
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.
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 ...
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.
?Reduce. Usage Reduce(f, x, init, right = FALSE, accumulate = FALSE)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With