Home > Net >  Series of n iterations using a for-loop in R
Series of n iterations using a for-loop in R

Time:06-06

For example: how could I generate 10 iterations that divides itself by half?

z <- 1
for(i in seq_along(1:10)) {
z[[i]] <- z * (1/2) 
}
z

This only provides me with the output of 0.50 and 0.25 and I'm not sure why

CodePudding user response:

Several things here:

  • z is a vector: so, if you do z * (1/2), this is going to affect the entire vector, you then have to also assign an index here.
  • You then need to do your for loop on n - 1 elements.
  • I would also suggest you to use [ rather than [[ here.

If you want a for loop, you should then do:

z <- 1
for(i in 1:9) {
  z[i   1] <- z[i] * (1/2) 
}

# z
# [1] 1.000000000 0.500000000 0.250000000 0.125000000 0.062500000 0.031250000 0.015625000 0.007812500 0.003906250 0.001953125

In R, there is often an easier solution than for loops. In this case you can use cumprod:

cumprod(c(1, rep(1/2, 9)))
# [1] 1.000000000 0.500000000 0.250000000 0.125000000 0.062500000 0.031250000 0.015625000 0.007812500 0.003906250 0.001953125
  • Related