0

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.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Apple_Tree
  • 49
  • 6

1 Answers1

2

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)
    }
}
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thanks for your response. The code seems to work, however, in the result I dont want it to break the simulation but simply add the result up till the point the 10th five is drawn. Apologies, I could have been a little bit clearer in my original post.Can you please suggest an edit to the above? – Apple_Tree Aug 22 '18 at 19:52
  • @Apple_Tree How do you propose the result to be? I could create a variable recording whether the 10th five was already drawn or not. – Rui Barradas Aug 22 '18 at 19:57
  • The final result should still show the output of 100 simulations. However, if within any of those simulations the 10th five was drawn then the result of that particular simulation should be the sum up till the point the 10th five was drawn. Thanks again. – Apple_Tree Aug 22 '18 at 20:07
  • @Apple_Tree Done, see if this is it. – Rui Barradas Aug 22 '18 at 20:32
  • 1
    You Sir are an absolute legend! Much appreciated. Im just in the process of googling parts of the above code to ensure I can upskill my R. – Apple_Tree Aug 22 '18 at 20:50