Mary Popko
Mary Popko

Reputation: 21

For Loop in R-Storing Values

I have to create a Monte Carlo simulation in R. I am simulating rolling a pair of dice 100 times in a row. I am supposed to see when the first roll that sums to seven usually occurs. When the first roll that sums to seven is rolled, I want to store this number and later find the average. I will run the simulation 100,000 times and then use the average to see how long it normally takes to roll the dice with a sum of seven. I am having trouble storing this value. Here is some peuedocode:

set.seed(101)
trials<-4 ## will later change to 100,000
for(j in 1:trials){ 
n=0 ## number of rolls
while(n<100){

n=n+1
result<-sum(sample(1:6,2,replace=TRUE)) ## rolling the dice

if(result==7) ## if sum is 7, print

print(n) ### not sure how to store the n value 
          ##to an array which i can later average

break
}

Any help on this would be greatly appreciated. Thank you

Upvotes: 1

Views: 437

Answers (1)

boyangeor
boyangeor

Reputation: 1151

In theory you might need more than 100 trials to reach a sum of 7 (it's highly unlikely to happen but still possible). So it's better to make it with while (TRUE) like this:

set.seed(101)

ntrials <- integer(1e+5)

for (i in seq_along(ntrials)) {

  n <- 0

  # Roll the dices until the sum is 7.
  while (TRUE) {

    n <- n + 1
    current.result <- sum(sample(1:6, 2, replace=T))
    if (current.result == 7) {
      ntrials[i] <- n
      break
    } 
  }
}

The amounts of necessary trials will be stored in ntrials.

Upvotes: 1

Related Questions