Aesler
Aesler

Reputation: 181

For loop or apply to save simulation results in a vector?

My code is for a simulation of 100 coin flips where if you lose your 10 dollar stake you are bankrupt (ie net win/loss reaches -10 within 100 flips, each flip is a 1 dollar bet). I want to run 500 times and then save the profit/loss results into one vector. I have my code mostly working for one flip, although I figure it might not be the most efficient way - would it be best to add a for loop or apply?

n=100
total.profit=c()
game.cashflow = cumsum(2*rbinom(n,1,prob=0.5)-1)
  if(length(game.cashflow[game.cashflow==-10])>0){
    game.profit=-10}else{
      game.profit=game.cashflow[1000]}

I want to save the results in a total.profit vector.

Upvotes: 0

Views: 489

Answers (1)

count
count

Reputation: 1338

Something like this?

flipit <- function(n) {
    res <- sample(c(-1,1),n,replace=TRUE)
    ifelse(any(cumsum(res)<=-10),"bust",sum(res))
}

replicate(500,flipit(100))

Upvotes: 2

Related Questions