Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Series of n iterations using a for-loop in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading