I would like to know if there is an implementation of the foldLeft function (and foldRight?) in R.
我想知道在R中是否有foldLeft函数(和foldRight?)的实现。
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函数适用于列表并具有以下签名:
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)
(我使用Scala List API的定义)
Does anybody know if such a function exists in R?
有人知道R中是否存在这样的功能吗?
2 个解决方案
#1
12
?Reduce. Usage Reduce(f, x, init, right = FALSE, accumulate = FALSE)
?减少。用法减少(f,x,init,right = FALSE,accumulate = FALSE)
#2
1
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
现在你可以将cumum重新定义为
cumsum(v) = foldl(function(x,y) { x+y }, v, 0)
To improve it you should handle missing values like Reduce
does.
要改进它,你应该处理像Reduce那样的缺失值。
#1
12
?Reduce. Usage Reduce(f, x, init, right = FALSE, accumulate = FALSE)
?减少。用法减少(f,x,init,right = FALSE,accumulate = FALSE)
#2
1
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
现在你可以将cumum重新定义为
cumsum(v) = foldl(function(x,y) { x+y }, v, 0)
To improve it you should handle missing values like Reduce
does.
要改进它,你应该处理像Reduce那样的缺失值。