简体   繁体   English

R 中的递归函数应用于向量

[英]recursive function in R applied to a vector

i'd like to know the most efficient (think code AND speed, in case i'd be running it on very very large vectors or objects) to compute a recursive function on an vector.我想知道最有效的(想想代码和速度,以防我在非常大的向量或对象上运行它)来计算向量上的递归函数。 (to compute S[i] we just need S[k] up to k<=(i-1) and V[k] with k<=i ) (要计算 S[i] 我们只需要 S[k] 到 k<=(i-1) 和 V[k] 与 k<=i )

a simple example would be given a num vector v of length N, to return a vector S where S[i] is the sum of the the first i elements of v.一个简单的例子是给定一个长度为 N 的 num 向量 v,返回一个向量 S,其中 S[i] 是 v 的前 i 个元素的总和。

in this particular case, a ( for ) loop is quite ugly...and ( edited ) so not efficient doing something like在这种特殊情况下,( for )循环非常丑陋……并且(已编辑)因此执行类似的操作效率不高

myfun <- function(i){sum(length_table[1:i])}
        S <- sapply(v,myfun))

is not good because of many unnecessary calculations ...不好因为很多不必要的计算......

any suggestions ?有什么建议 ?

EDIT: to me there is not much too much difference between iterative and recursive.编辑:对我来说,迭代和递归之间没有太大区别。 i didn't know about the cumsum function which solves the problem in this particular case.我不知道在这种特殊情况下解决问题的 cumsum 函数。

ok now let's have a more general case where we have a (num) function f which takes two (num) arguments so f(x,y) is also a num value.好的,现在让我们有一个更一般的情况,我们有一个 (num) 函数 f,它接受两个 (num) 参数,所以 f(x,y) 也是一个 num 值。 we need a num "seed" as well.我们还需要一个“种子”。 given a num vector v of length N,给定一个长度为 N 的 num 向量 v,

i'd like to construct the vector U defined by我想构造由定义的向量 U

U[1] = f(v[1],seed)
U[2] = f(v[2],U[1])
U[3] = f(v[3],U[2])...

U[N] = f(v[N],U[N-1])

is there a nice efficient way to do that without looping ?有没有一种很好的有效方法来做到这一点而不循环?

Here are two ways to implement this in R (and while Reduce might seem to be more elegant, my experience is that it is more prone to (my) confusion):这里有两种在 R 中实现的方法(虽然 Reduce 看起来更优雅,但我的经验是它更容易(我的)混淆):

> y <- numeric(); y[1] <- 1; for( i in 2:10 ){ y[i] <- 3+y[i-1]*2}
> y
 [1]    1    5   13   29   61  125  253  509 1021 2045

> Reduce( function(x,y){ y= 3+ x*2}, 1:10, accumulate=TRUE)
 [1]    1    5   13   29   61  125  253  509 1021 2045

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM