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)
(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...
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...
According to the loop invariant theorem, a valid loop invariant ?(?)I(n) must have the property that...
According to the loop invariant theorem, a valid loop invariant ?(?)I(n) must have the property that Select one: a. ?(?)=0I(n)=0 after a finite number of steps. b. After the loop, ?→?(?)P→I(N) where ?P is the postcondition. c. ?(0)→?I(0)→Q, where ?Q is the precondition. d. None of the other answers are correct
Need to HAVE a web page that uses a loop to allow a teacher to enter...
Need to HAVE a web page that uses a loop to allow a teacher to enter the following information for all students in a class: student's name, mt  grade, f  grade, hW grade, attendance grade. program should calculate each student's numeric total grade based on the following formula:course grade = (mT*0.3)+(f*0.4)+(homework*0.2)+(attendance*0.1)File Table.html looks like this:When the button is clicked, you need to prompt the user the following information:-number of students (which will determine the number of rows in your table)-student's name-mT grade-f...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT