Home > front end >  Have for loop in r skip some values
Have for loop in r skip some values

Time:12-07

I have the following issue where I can't find the solution to:

  • I have a data frame including N sample sizes (call it 'size' for now) that I calculated in a previous loop
  • I made a new loop and for each for each value of 'size' I want to calculate some things. Did that the following way:
samplesize <- numeric(N)

for (i in 1:N){
 samplesize <- size[i,]

 # Make storage for the calculated values
 store <- matrix(data = NA, nrow = samplesize, ncos = N)

 # Get random number from normal distribution N times
 for (a in 1:N){
  store[,i] <- rnorm(n = samplesize, mean = avg, sd = stdvn)
 }
}

As you can see, I plug in the current value of 'size' in the loop to make some storage and to get some random numbers. However, the problem is that some values for 'size' are zero. That results in an error for making 'store', since I ask if it wants to make zero rows. Then, it also gives an error for getting the random number, since I ask for a n of 0. I need to add the numbers of 'store' to previously calculated values, and it is therefore not desirable to turn the zero's into ones, because then I would add an additional value while is should actually be zero. I think what I want is that the loop skips all the values of 'size' that are zero. Does anyone have a solution on how to do that? Thanks a lot in advance!

CodePudding user response:

I think what you're looking for maybe is the next command paired with if to do a test:

for (i in 1:10) {
  if(i == 3) {
    next
  }
  print(i)
}
#> [1] 1
#> [1] 2
#> [1] 4
#> [1] 5
#> [1] 6
#> [1] 7
#> [1] 8
#> [1] 9
#> [1] 10

(Run with some quick sample code, as I can't quite run your example without your previous data. If it's not working, you could try adding some sample data to your question - size, N, avg and stdvn I think is what you're calling here but not defined.

Created on 2021-12-07 by the reprex package (v2.0.1)

  • Related