Sonny
Sonny

Reputation: 11

Repeating a Function within a Function in R

I have a function that runs a simulation a number a times. It creates a matrix of 0s and 1s and then checks for a 'TIC TAC TOE' win. I want to be able to repeat that function 'n' number of times. Here is my code...

    function (SimSize,nrow,ncol)
{
count.win = 0
#Beginning Grand Loop
for(i in 1:SimSize){

#creating TicTacToe board of 1s and 0s
game = matrix(sample(c(0,1),replace=T,size = nrow*ncol),nrow=nrow)

#Check for any wins

if( any( 
any(colSums(game)==ncol),
any(rowSums(game)==nrow),
any(sum(diag(game))==ncol),
any(sum(diag(apply(game,2,rev)))==ncol))
)
count.win = count.win+1
}
#calculate the probability of a win per simulation size
p.win = count.win/SimSize
out = list(SimSize,count.win,p.win)
out
}

I want to be able to plot a SimSize vs count.win graph at the end. But to do that I need the selected SimSize to be run 'n' times. Any help??

Upvotes: 1

Views: 87

Answers (2)

Robert Kirsten
Robert Kirsten

Reputation: 494

tictactoe_simulation <- function (sim_size, n_row, n_col) {
  count.win = 0

  #Beginning Grand Loop
  for(i in 1:sim_size){
    #creating TicTacToe board of 1s and 0s
    game = matrix(sample(c(0,1),replace=T,size = nrow*ncol),nrow=nrow)

    #Check for any wins
    if( any( 
      any(colSums(game)==ncol),
      any(rowSums(game)==nrow),
      any(sum(diag(game))==ncol),
      any(sum(diag(apply(game,2,rev)))==ncol))
    )
      count.win = count.win+1
  }
  #calculate the probability of a win per simulation size
  p.win = count.win/SimSize
  out = list(SimSize,count.win,p.win)
  out
}
replicate(10, tictactoe_simulation(10,3,3))

Another solution could be closures, where you define in an outer funtion the amount of runs and in the inner the set up for the simulation. see

Additionally, I would suggest naming your variables in camelCase or with underscore. Especially in the case of nrow and ncol which are base functions.

Upvotes: 0

Dean MacGregor
Dean MacGregor

Reputation: 18416

If I assume you assign your function as tictac<-function(SimSize,nrow,ncol) {}

then you could simply do

results<-lapply(1:100,function(x) tictac(x,3,3))

You will want to change your function so that its only output is count.win

Upvotes: 1

Related Questions