Search code examples
rfor-loopmontecarlo

How to bind resultant columns to a data frame in for loop?


I want perform monte-carlo simulations for 12 iterations with mean varying from 5 to 60 by an interval of 5. As an output of the following code I want each simulation result in a different columns as a data frame. For instance, if I want to perform 10,000 simulations for each set of mean and std.dev, the resultant dataframe will have 12 columns and 10000 rows. The code is:

df<-data.frame()
for (i=5; i<=60; i=i+5)
  {
  {
    cvsq=1
    mcs=rnorm(10000,i,(i*cvsq))
    op$i<-data.frame(mcs)
  }
  df<-cbind(op)
  }
df

The results from this code is a data frame with two columns with simulation results for 60 and 5 only.


Solution

  • Can use lapply and do.call

    DF <- do.call(cbind, 
            lapply(seq(5,60,5), function(i) setNames(data.frame(rnorm(10000, i, (i*cvsq))), i))
    )
    
    head(DF)
           5      10     15       20     25      30    35     40      45     50      55     60
    1  2.621  9.3083  7.004 -20.4034  43.77  -6.906 15.68  60.42 -30.981 55.634  -2.329 156.45
    2  3.490 -4.1331  9.461  24.7668  15.06  69.660 15.48 132.71  21.109  8.984  84.382  63.27
    3  4.863 -0.8772  3.649   0.2247  14.01  16.365 81.56 -19.01  27.993 15.910  13.690 106.21
    4  4.516 17.0948 -2.754   9.7998  37.01  76.459 56.19  26.39  80.759 54.173  13.152  34.03
    5 11.110 16.7807 39.529  -2.9710 -11.61 -10.982 68.50  48.68  53.811 30.779  78.196 -36.90
    6 -3.297  1.0127 15.150  37.9734  11.31  45.855 58.18  22.91   5.654 66.101 -35.472  68.05