简体   繁体   中英

How to use a while loop before assigning the outcomes to a vector in R?

My simulated experiment is as follows:

  1. Roll a fair die to get a number X between 1 to 6.
  2. Flip a fair coin X number of times (ie the number from the die roll) and record the number of heads.

This is the code (within a loop) for my experiment:

Youtcomes <- rep(0, 100)
for (i in 1:100) {
    X <- sample(1:6, 1, replace=TRUE, rep(1,6)/6)
    Y <- sample(c("H", "T"), X, replace=TRUE, rep(1,2)/2)
    # assign output inside the loop with [i] indexing
    Youtcomes[i] <- sum(Y == "T")
}

I'm sure this isn't the most efficient loop but unfortunately, I have been instructed to do it this way.

I then need to create a random variable N that is defined as the number of runs of the experiment until an outcome Y>=5 occurs for the first time.

How would I go about designing a loop to simulate this value?

You can use a while loop as follows:

one.simulation <- function() {
    N <- 0
    Y <- 0
    while (Y < 5) {
        X <- sample(6, 1)
        Y <- sum(sample(c(Heads = 1, Tails = 0), X, replace=TRUE))
        N <- N+1
    }
    N
}

set.seed(1234)
one.simulation()
# [1] 50

replicate(100, one.simulation())
#   [1]  20   9  11  57  35  35  14 106  11  14   6 113   8  28 125  29   4  12   3
#  [20]  19  39   4  13  32  23  96  19  20  47  68  96  65  18  71  39  51   6  22
#  [39] 111   3 109   9  22  18  99   1 151  85   3   2 102  46  18  31  41  21  14
#  [58]  75  10  56   3  63  79  12  59  68  31  47  35  15  14  38  11  36  26  24
#  [77]  24  45  43  15  81   1  16  57  29   6  64  11  15  47 107 116   8  62 146
#  [96] 217  78  28   9 141

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM