Anakin Skywalker
Anakin Skywalker

Reputation: 2520

Breaking while loop, reaching a certain randomly generated value in R

Writing a while loop in R.

I have an initial value and I need to simulate a sample (size must be unlimited though, not 100).

When a sample hits a necessary value, I would like to break the loop and print a message.

My logic is the following:

my_start <- 1000 # inital value
random <- sample(my_start, size = 100, replace = FALSE, prob = NULL) 
# sample simulation, but size must be not 100, but unlimited
while (result > 2000) {
result <- my_start + random # trying here to add a sample to initial value
print('Start reaches', result)
}

Plus I would like the distribution of the sample would not exceed 100.

I appreciate any tips!

UPDATED: Almost reached the goal with the help of another user, just want that the fluctuation of value would not be more than a certain value (100), not purely random. For instance, it will fluctuate between 900 and 1000 and when it hits 1050, it will break.

my_start <- 1000 # inital value
result <- my_start
n <- 2000 # generate random number from 1 to this value

while (result < 2000) {
random <- sample(n, 1)
result <- random
cat('\nValue reaches', result)
}

Upvotes: 0

Views: 248

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

Probaly, this is what you want :

my_start <- 1000 # inital value
result <- my_start
n <- 100 #generate random number from -n to n

set.seed(123)
while (result < 2000) {
  random <- sample(-n:n, 1)
  result <- result + random
  cat('\nValue reaches', result)
}

#Value reaches 1058
#Value reaches 1136
#Value reaches 1049
#Value reaches 1143
#Value reaches 1212
#...
#...
#Value reaches 966
#Value reaches 906
#Value reaches 980
#Value reaches 969
#Value reaches 928
#Value reaches 843
#Value reaches 858
#...
#...
#Value reaches 1952
#Value reaches 1973
#Value reaches 2015

Upvotes: 1

Related Questions