Reduce left-fold in R
fold, higher-order-functions, lambda, r
Solution
This is what you want (if using `Reduce` - clearly not the right thing to do for this particular case, so this is for demonstration purposes only):
Reduce(function(x,y) {x+y-5}, v, 0)
This will start at the left of `v`, will add the next element and subtract 5 and will keep doing that until it reaches the end of `v`.
You should be able to see how you can modify to put an arbitrary function of the two elements (the accumulated one and the next one) instead of the one you chose for your question.
Problem
I am using the higher-order function to apply a function to every element in a vector and return the result as a scalar value. Suppose I have: ``` v = c(0, 1, 2, 3, 4, 5, 6, 7, 8) ``` I want to compute the sum of all these integers centered 5 integers to the left: SUM(i-5) for i in v: ``` Reduce(function(i) sum(i-5), v, 0) ``` I get the following error: `Error in f(init, x[[i]]) : unused argument(s) (x[[i]])` What is going wrong with my lambda function? Thanks!