R中的循环 - 需要使用索引,反正避免“for”? [英] Loops in R - Need to use index, anyway to avoid 'for'?
问题描述
我知道在R中使用 for
循环不是最好的做法,因为它没有增强的性能。几乎所有的情况下都有一个 * apply
这个函数解决了我们的问题。
然而,面临的情况,我没有看到一个解决方法。
我需要计算连续值的百分比变化:
< (x)= {
pv [i] < - (x [i ] - x [i-1])/ x [i-1]
}
所以,你可以看到,我必须同时使用 x [i]
元素,而且 x [i-1]
元素。通过使用 * apply
函数,我只是看到如何使用 x [i]
。有没有反正我可以避免为
循环?
所提供的将是分数变化,但如果你乘以100,你会得到百分比变化:
pre $ pv < - vector长度(x))
pv [1] < - 0
pv [-1] < - 100 *(x [-1] - x [-length(x)] )/ x [-length(x)]
向量化解决方案。 (你应该注意到,for循环会像应用解决方案一样慢......只是不够漂亮,总是寻找一个向量化的方法。)
解释更多: x [-length(x)]
是向量, x [1:(length {x-1) ]
, x [-1]
是向量, x [2:length(x)]
,并且R中的向量操作和你的for循环体一样,虽然不使用显式循环。 R首先在这些移位向量中构造差异,然后除以
x [ 1:(length {x-1)]
。
I know it's not the best practice in R to use the for
loop because it doesn't have an enhanced performance. For almost all cases there is a function of the family *apply
that solves our problems.
However I'm facing a situation where I don't see a workaround.
I need to calculate percent variation for consecutive values:
pv[1] <- 0
for(i in 2:length(x)) {
pv[i] <- (x[i] - x[i-1])/x[i-1]
}
So, as you can see, I have to use both the x[i]
element, but also the x[i-1]
element. By using the *apply
functions, I just see how to use the x[i]
. Is there anyway I can avoid the for
loops?
What you offered would be the fractional variation, but if you multiplied by 100 you get the "percent variation":
pv<- vector("numeric",length(x))
pv[1] <- 0
pv[-1] <- 100* ( x[-1] - x[-length(x)] )/ x[-length(x)]
Vectorized solution. ( And you should note that for-loops are going to be just as slow as *apply solutions ... just not as pretty. Always look for a vectorized approach.)
To explain a bit more: The x[-length(x)]
is the vector, x[1:(length{x-1)]
, and the x[-1]
is the vector, x[2:length(x)]
, and the vector operations in R are doing the same operations as in your for-loop body, although not using an explicit loop. R first constructs the differences in those shifted vectors, x[-length(x)] - x[-1]
, and then divides by x[1:(length{x-1)]
.
这篇关于R中的循环 - 需要使用索引,反正避免“for”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!