Home > OS >  R: Printing Every 5th Output of a Loop
R: Printing Every 5th Output of a Loop

Time:09-17

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.):

[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!

CodePudding user response:

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)
  }
}
  • Related