Reputation: 13
I am trying to sample from a sequence from 0 to 36. But i want the loop to terminate if 0 is sampled. This is what i have done so far and it does not work,
x <- seq ( 0, 36, by=1 )
for ( i in 1:100) {
x<- sample (x, 1, replace = F, prob=NULL)
if (x[i] == 0){
break
}
print("x[i]")
}
Thanks, Pilara
Upvotes: 0
Views: 57
Reputation: 1631
I'm just tweaking your code a little bit. Just use another variable for storage.
x <- seq ( 0, 36, by=1 )
y <- c()
for ( i in 1:100) {
y[i]<- sample (x, 1, replace = F, prob=NULL)
if (y[i] == 0){
break
}
print(y[i])
}
Hope this helps.
Upvotes: 1
Reputation: 1790
You have to store all the outcomes of your sampling process in a vector. You could do it like this:
set.seed(12345) # Set seed to make results reproducible.
# Change the seed for different random numbers
x <- seq(0, 36, by = 1)
y <- sample(x, 1) # Initialize vector of sampling results
while (tail(y, 1) != 0){
y <- c(y, sample(x, 1)) # Append results to vector
}
> y
# [1] 26 32 28 32 16 6 12 18 26 36 1 5 27 0
Upvotes: 1