Skip to content

How do I fix this ?

2 messages · eric, Pete Brecknock

#
Just when I think I'm starting to learn ....

Statement z1 works, statement z doesn't. Why doesn't z work and what do I do
to fix it ? Clearly the problem is with the first NA, but I would think it's
handled through the loop vectorization.


y1 <- rnorm(20, 0, .013)

y1
 [1] -0.0068630836 -0.0101106230 -0.0169663344 -0.0066314769  0.0075063818
 [6] -0.0033548024  0.0015647863  0.0119815982 -0.0021430336  0.0044617167
[11]  0.0053447708 -0.0005590323  0.0063195781  0.0073059640 -0.0181872678
[16] -0.0098094568  0.0013679040 -0.0028490887 -0.0131129191  0.0126610358

z1 <- ifelse(is.na(y1), 10000, 10000*cumprod(1+y1))

z1
 [1] 9931.369 9830.957 9664.162 9600.074 9672.136 9639.688 9654.772 9770.451
 [9] 9749.513 9793.012 9845.354 9839.850 9902.034 9974.378 9792.971 9696.907
[17] 9710.172 9682.506 9555.541 9676.524



y <-c(NA, rnorm(19,0, .013))

y
 [1]            NA  0.0056258152 -0.0117690116  0.0163961630  0.0007818773
 [6]  0.0007761957  0.0139769376  0.0041086982 -0.0049545337  0.0059587216
[11] -0.0079022056  0.0083076357 -0.0075823658  0.0173806814 -0.0034915869
[16] -0.0045480358  0.0168642491  0.0038681635 -0.0123010077  0.0087494624

z <-ifelse(is.na(y), 10000, 10000*cumprod(1+y))

z
 [1] 10000    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
[13]    NA    NA    NA    NA    NA    NA    NA    NA
#
Eric

Your problem lies in the way cumprod deals with NAs

If you look at ?cumprod you will see 
"An NA value in x causes the corresponding and following elements of the
return value to be NA"

Not sure what behaviour you want to see on encountering an NA (ignore it,
restart the cumprod process, .....). Making things easy for myself (it's
late), if you wish to simply ignore an NA the following would work

# sample data
y2=c(NA,1,2,3,4,5)

# ignore NA
ave(y2,is.na(y2),FUN=cumprod)

HTH

Pete