I want to write a for
loop that iterates over a vector
or list
, where i'm adding values to them in each iteration. i came up with the following code, it's not iterating more than 1 iteration. i don't want to use a while
loop to write this program. I want to know how can i control for loops iterator. thanks in advance.
steps <- 1
random_number <- c(sample(20, 1))
for (item in random_number){
if(item <18){
random_number <- c(random_number,sample(20, 1))
steps <- steps 1
}
}
print(paste0("It took ", steps, " steps."))
CodePudding user response:
It depends really on what you want to achieve. Either way, I am afraid you cannot change the iterator on the fly. while
seems resonable in this context, or perhaps knowing the plausible maximum number of iterations, you could proceed with those, and deal with needless iterations via an if statement. Based on your code, something more like:
steps <- 1
for (item in 1:100){
random_number <- c(sample(20, 1))
if(random_number < 18){
random_number <- c(random_number,sample(20, 1))
steps <- steps 1
}
}
print(paste0("It took ", steps, " steps."))
Which to be honest is not really different from a while()
combined with an if statement to make sure it doesn't run forever.
CodePudding user response:
This can't be done. The vector used in the for
loop is evaluated at the start of the loop and any changes to that vector won't affect the loop. You will have to use a while
loop or some other type of iteration.