Reputation: 109
I have this code and i am wondering if it can be executed without the while loop.
quantity <- vector()
while (length(quantity) < 2) {
Random <- runif(10, 0, 1)
quantity <- which(Random < 0.3)
}
quantity
Upvotes: 2
Views: 72
Reputation: 72583
You could define a recursive function.
set.seed(42)
foo <- function() {
random <- runif(10, 0, 1)
quantity <- which(random < .3)
if (length(quantity) >= 2) return(quantity)
else return(foo())
}
foo()
# [1] 3 8
Check:
set.seed(42)
quantity <- vector()
while (length(quantity) < 2) {
Random <- runif(10, 0, 1)
quantity <- which(Random < 0.3)
}
quantity
# [1] 3 8
Upvotes: 2