In: Statistics and Probability
I need to generate a loop for 1,000 Monte Carlo iterations in R. I have two randomly generated standard normal variables for this with sample sizes of 100.
If you don't insist on using the MonteCarlo package (which is new to me and looks interesting) you could wrap your code into a function.
First, creating a random matrix with only the desired 90%-row. Then, after specifying the amount, you can do the iterations and pack them into a list with lapply(). At the end just create an other matrix with your (rounded) statistics.
Something like this:
set.seed(54897) # setting seed for sake of reproducibility probability.sequence <- seq(0.1, 0.90, 0.1) # iteration function mx <- function(X, n) { random.sample <- sample(1:1e2, 1e3, replace = TRUE) a = matrix(random.sample, nrow = 10, ncol = 10, byrow = TRUE) b <- apply(a[ ,1:10], 2, SMA, n = 3) c <- pmax(a, b) d <- apply(c, 2, quantile, probs = probability.sequence, na.rm = TRUE) return(d[9, ]) # returns only the desired 90 % row } # amount of iterations amount <- 1e3 # iteration mx.lst <- lapply(1:amount, mx) # matrix for statistics r = matrix(NA, nrow = 1, ncol = 4, dimnames = list(NULL, c("mean", "variance", "Upper CL", "Lower CL"))) r[, 1] <- (mean(unlist(lapply(mx.lst, mean)))) # mean r[, 2] <- sqrt(var(unlist(lapply(mx.lst, mean)))) # variance r[, 3] <- r[, 1] - 1.96 * sqrt(r[, 2]) # lower CI 95 % r[, 4] <- r[, 1] + 1.96 * sqrt(r[, 2]) # upper CI 95 % # output (monte.carlo.aggregate.results <- round(r, 0)) # mean variance Upper CL Lower CL # [1,] 82 3 78 86 str(monte.carlo.aggregate.results) # num 1, 1:4] 82 3 78 86 # - attr(*, "dimnames")=List of 2 # ..$ : NULL # ..$ : chr [1:4] "mean" "variance" "Upper CL" "Lower CL" # speed test amount <- 1e4 system.time(mx.lst <- lapply(1:amount, mx)) # user system elapsed # 48.21 0.00 48.31
Note: please check yourself if the used formula for the confidence interval fits to your needs.