是否可以对 R 中向量元素的顺序更新进行向量化? [英] Is it possible to vectorise the sequential update of the elements of a vector in R?
问题描述
是否可以像下面这样对代码进行矢量化处理?
Is it possible to vectorise code like the following?
length(x) <- 100;
x[1] <- 1;
y <- rnorm(100);
for(i in 2:100) {
x[i] <- 2 * y[i] * x[i-1];
}
我明白这是一个微不足道的例子,但它有助于说明这个想法.
I appreciate that this is a trivial example, but it serves to illustrate the idea.
我经常需要编写代码,其中向量中的第 i 个值取决于第 (i-1) 个值,如果可能,我想编写此代码而不需要 for
循环,因为分析表明具有此类操作的函数是我代码中的主要瓶颈.
I often need to write code where the i-th value in a vector depends on the (i-1)-th value and if possible, I'd like to write this without needing a for
loop, as profiling suggests the functions with this type of operation are the major bottlenecks in my code.
这个操作是否可以向量化,所以我不需要在计算中使用 for()
循环?
Is this operation vectorizable so I do not need to use a for()
loop in the calculation?
推荐答案
一般来说,如果你想要一个矢量化的解决方案,你需要解决 递归关系.
In general, if you want a vectorised solution you need to solve the recurrence relation.
这篇关于是否可以对 R 中向量元素的顺序更新进行向量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!