title: Creating a function to characterise repeated simulations
body: <p>I want to create a function which helps characterise the results to some simulations. For the purposes of this post let the simulation function be:</p>
  <pre><code>example_sim &lt;- function(time=100, npops=5){
    result &lt;- data.frame(matrix(NA, nrow = time, ncol = npops))
    colnames(result) &lt;- LETTERS[1:npops]
    for(i in 1:npops){
      sim &lt;- sample.int(time, time)
      result[,i] &lt;- sim
      result[,i] &lt;- result[,i]*i
    }
    return(result)
  }
  </code></pre>
  <p>This creates a data frame with varying length and width based on the number of populations (npops) and the time simulated.</p>
  <p>I want to create a function which uses the output of such simulations and characterises the mean, variance for each population over an n amount of simulations (nsims).</p>
  <p>So far I have managed to get it working for two populations with the following code:</p>
  <pre><code>library(&quot;matrixStats&quot;)
  library(&quot;reshape2&quot;)
  
  ensembles &lt;- function(nsims=10, time = 100, npops = 2){
    result_N.A &lt;- data.frame(matrix(NA, nrow = time, ncol = nsims))
    result_N.B &lt;- data.frame(matrix(NA, nrow = time, ncol = nsims))
    for( i in 1:(nsims)){
      simulation_with_2pops &lt;- example_sim(time=100,npops=2)
      result_N.A[,i] &lt;- simulation_with_2pops[,1]
      result_N.B[,i] &lt;- simulation_with_2pops[,2]
    }
    output &lt;- simulation_with_2pops
    for( j in 1:params$ntime){
      output$meanA[j] &lt;- rowMeans(result_N.A[j,])
    }
    for( j in 1:params$ntime){
      output$meanB[j] &lt;- rowMeans(result_N.B[j,])
    }
    for( j in 1:params$ntime){
      output$varA[j] &lt;- rowVars(as.matrix(result_N.A[j,]))
    }
    for( j in 1:params$ntime){
      output$varB[j] &lt;- rowVars(as.matrix(result_N.B[j,]))
    }
    return(output)
  } 
  ensembles_output&lt;- ensembles(nsims = 10)
  ensembles_output
  </code></pre>
  <p>To fully implement the function for any number of populations I would need to create another for loop where I create and update the <code>result_N.A</code> object. (Presumably called something like <code>result[i]</code>.)
  I have also thought about creating a 3 dimensional object (time, npops, nsims) and taking a slice of it to calculate the mean and variance but i havent had much success yet.
  I am not married for this route and am very open to other recommendations.</p>
  <p>Eventually I would like to create a code where the covariance and correlation are also calculated by giving highlighting two populations in the parameters. (for instance population A and population E). If you have any ideas on the implementation i would be very grateful to hear them.</p>
  <p>Thank you for considering this problem.</p>