重复R中函数内的函数

时间:2015-11-11 16:38:10

标签: r

我有一个运行模拟次数的函数。它创建一个0和1的矩阵,然后检查'TIC TAC TOE'胜利。我希望能够重复这个功能'n'次。这是我的代码......

    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
}

我希望能够在最后绘制一张SimSize vs count.win图。但要做到这一点,我需要选择的SimSize运行'n'次。任何帮助?

2 个答案:

答案 0 :(得分:1)

如果我假设您将功能指定为tictac<-function(SimSize,nrow,ncol) {}

然后你可以简单地做

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

您需要更改功能,使其仅输出count.win

答案 1 :(得分:0)

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.