Search code examples
rconditional-statementssimulationmultinomial

Multinomial Simulation


I am currently running a multinomial simulation 100 times in R with outcomes 2,3,4,5 each with a certain probability. My objective is to draw 120 times with each draw resulting in only one of the aforementioned outcomes. Finally, I sum the results of the simulation. I have been able to achieve this compactly using the following code:

> y<-c(2,3,4,5)
> replicate(100, sum(rmultinom(120,size=1,prob=c(0.1,0.2,0.6,0.1))*y))

However, I want to add the additional conditionality that if outcome 5 (the last row with probability 0.1) is drawn 10 times in any simulation run then stop the simulation (120 draws) and simply add the result as per above.

Any help on how to incorporate this conditionality in the above code would be much appreciated.


Solution

  • Maybe there are better ways to do what the OP asks for but I believe the following does it.

    set.seed(4062)    # Make the results reproducible
    
    y <- c(2, 3, 4, 5)
    n <- 100
    m <- integer(n)
    
    for(i in 1:n){
        r <- rmultinom(120, size = 1, prob = c(0.1, 0.2, 0.6, 0.1))*y
        if(sum(r == 5) >= 10){
            r <- apply(r, 2, function(x) x[x != 0])
            j <- which(r == 5)[10]
            m[i] <- sum(r[seq_len(j)])
        }else{
            m[i] <- sum(r)
        }
    }