[R] Vectorization
Petr Savicky
savicky at praha1.ff.cuni.cz
Mon Jan 24 09:24:11 CET 2011
On Sun, Jan 23, 2011 at 07:29:16PM -0800, eric wrote:
>
> Is there a way to vectorize this loop or a smarter way to do it ?
>
> y
> [1] 0.003990746 -0.037664639 0.005397999 0.010415496 0.003500676
> [6] 0.001691775 0.008170774 0.011961998 -0.016879531 0.007284486
> [11] -0.015083581 -0.006645958 -0.013153103 0.028148639 -0.005724317
> [16] -0.027408025 0.014767422 -0.001619691 0.018334730 -0.009747171
>
> x <-numeric(length(y))
> for (i in 1 :length(y)) {
> x[i] <- ifelse( i==1, 10000*(1+y[i]), (1+y[i])*x[i-1])
> }
>
> x
> [1] 10039.907 9661.758 9713.912 9815.087 9849.447 9866.110 9946.724
> [8] 10065.706 9895.802 9967.888 9817.536 9752.289 9624.016 9894.919
> [15] 9838.278 9568.630 9709.934 9694.207 9871.948 9775.724
>
> Basically trying to see how the equity of an investment changes after each
> return period. Start with $10,000 and a series of returns over time. Figure
> out the equity after each time period (return).
Hello.
The cycle computes a cumulative product. The initialization may
be add as a common multiplier. So, z in the following should be equal
to x up to the machine rounding error.
y <- c(
0.003990746, -0.037664639, 0.005397999, 0.010415496, 0.003500676,
0.001691775, 0.008170774, 0.011961998, -0.016879531, 0.007284486,
-0.015083581, -0.006645958, -0.013153103, 0.028148639, -0.005724317,
-0.027408025, 0.014767422, -0.001619691, 0.018334730, -0.009747171)
x <- numeric(length(y))
for (i in 1:length(y)) {
x[i] <- ifelse(i==1, 10000*(1+y[i]), (1+y[i])*x[i-1])
}
z <- 10000*cumprod(1 + y)
max(abs(x - z))
# [1] 1.818989e-12
Petr Savicky.
More information about the R-help
mailing list