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

R: Printing Every 5th Output of a Loop

I am working with the R programming language.

I have this loop:

for (i in 1:100) 

{
num_i = as.integer(rnorm(1,100,100))
print(num_i)
}

[1] 44
[1] -3
[1] -55
[1] 127
[1] 149
[1] 83
[1] 151
[1] 52
[1] 120
[1] 102
[1] 132
[1] 352
[1] 96
[1] 208
[1] 268
[1] 156
[1] 51
[1] 23
[1] 27

I only want to print every 5th output of this loop (i.e. 5th output, 10th output, 15th output, etc.):

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

[1] 83
[1] 132
[1] 156

I had an idea – I could use the concept of "modulo" in such a way, such that only every 5th output is printed. For example:

for (i in 1:100) 

{

num_i = as.integer(rnorm(1,100,100))
ifelse(i %% 5 == 0, print(num_i), "" )

}

Have I done this correctly?

Thanks!

>Solution :

There are non-loop ways to do this to get the same output since rnorm can generate more than 1 number.

However, this seems to be a simplified example of what you are doing so in this case, you can continue the for loop using if/else

for (i in 1:100) {
  num_i = as.integer(rnorm(1,100,100))
  if(i %% 5 == 0) {
    print(num_i)
  }
}

This will print nothing when the condition i %% 5 is FALSE. If you want it to print "" you may include the else condition.

Or since we are not using num_i when the condition is not satisfied so in this case we can generate the number only when i %% 5 == 0

for (i in 1:100) {
  if(i %% 5 == 0) {
    num_i = as.integer(rnorm(1,100,100))
    print(num_i)
  }
}
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