Question

In: Statistics and Probability

I need to generate a loop for 1,000 Monte Carlo iterations in R. I have two...

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.

Solutions

Expert Solution

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.


Related Solutions

preform a Monte Carlo simulation in R to generate the probability distribution of the sum of...
preform a Monte Carlo simulation in R to generate the probability distribution of the sum of two die (for example 1st die is 2 and second die is 3 the random variable is 2+3=5). The R-script should print out (display in R-studio) or have saved files for the following well labeled results: 1. Histrogram or barchart of probability distribution 2. Mean of probability distribution 3. Standard deviation of probability distribution
Perform Monte Carlo integration using R statistical programming to estimate the value of π. Generate N...
Perform Monte Carlo integration using R statistical programming to estimate the value of π. Generate N pairs of uniform random numbers (x,y), where x ∼ U(0,1)and y ∼ U(0,1) and each (x,y) pair represents a point in the unit square. To obtain an estimate of π count the fraction of points that fall inside the unit quarter circle and multiply by 4. Note that the fraction of points that fall inside the quarter circle should tend to the ratio between...
How and when do you use the Monte Carlo analysis? Does it have anything to do...
How and when do you use the Monte Carlo analysis? Does it have anything to do with understanding the probability of a risk occurring as well?
using matlab can you show me an example of a monte carlo that has two things...
using matlab can you show me an example of a monte carlo that has two things randomizing?
Use Monte Carlo method (discounted expected value) to price a butterfly spread with=9,10,11,T−t=0.125,S=9and r=0.08, volatility=0.4first without...
Use Monte Carlo method (discounted expected value) to price a butterfly spread with=9,10,11,T−t=0.125,S=9and r=0.08, volatility=0.4first without Antithetic Sampling (100 N’s)
I have a problem with the code for my project. I need the two clients to...
I have a problem with the code for my project. I need the two clients to be able to receive the messages but the code I have done only the server receives the messages. I need the clients to be able to communicate with each other directly not throught the server. The requirements of this "local chat" program must meet are: 1. The chat is performed between 2 clients and a server. 2. The server will first start up and...
(This is for java) I need to rewrite this code that uses a while loop. public...
(This is for java) I need to rewrite this code that uses a while loop. public class Practice6 {      public static void main (String [] args) {         int sum = 2, i=2;        do { sum *= 6;    i++;    } while (i < 20); System.out.println("Total is: " + sum); }
My Java program keeps "running." I know I need to close a "loop" but I can't...
My Java program keeps "running." I know I need to close a "loop" but I can't find it. I'm learning how to code. This is confusing for me. import java.util.Scanner; import java.util.ArrayList; public class SteppingStone4_Loops {    public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String recipeName = ""; ArrayList<String> ingredientList = new ArrayList(); String newIngredient = ""; boolean addMoreIngredients = true; System.out.println("Please enter the recipe name: "); recipeName = scnr.nextLine();    do {    System.out.println("Would you...
in this code I have used array two times . I need a way to make...
in this code I have used array two times . I need a way to make the program functional using a string to store the results and print it again later . this game should be array free. import java.util.Scanner; import java.util.Random;//starter code provided public class inputLap { public static char roller; public static String playerName; public static int printed=0; public static int rounds=8,lives=0,randy; public static int tries[]=new int[4];//use arrays to store number of tries in each life public static...
My question is if n<r when there is no loop. I can't enter numbers again.Where is...
My question is if n<r when there is no loop. I can't enter numbers again.Where is the problem? How do it? #include int fact(int no) { if (no == 0) return 1; return no * fact(no - 1); } int calc(int n, int r,int *com,int *per) //as given in question formula of permutation n!/(n-r)! { *com=fact(n)/(fact(r)*fact(n-r)); *per=fact(n)/fact(n-r); } int main() { int n=0,r=0,co,pe; while(n<=0 || r<=0) { printf("Enter N value:"); scanf("%d",&n); printf("Enter R value:"); scanf("%d",&r); if(n { printf("N value should...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT