Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using the nested for loops(i.e. for loop defined inside a for loop) to demonstra

ID: 3864138 • Letter: U

Question

Using the nested for loops(i.e. for loop defined inside a for loop) to demonstrate the law of large numbers with R.

(a) Take sample from X~Uniform(3,7).

(b) Run your outer for loop from 10 to 2010 with step size 100 so that the sample size gets increased: n=10,110,210,...,2010

(c) Run the inner for loop to construct the sampling distribution of the mean with 100000 random numbers.

(d) Compute mean of the sampling distribution and standard deviations for each n in the outer loop and print them out one row, (e.g. print(c(mean,std)).

(e) Generate the histogram for each sample size n with fixed xlim=c(3.5,6.5) in the outer loop.

You may use par(mfrow=c(3,3)) before the loops begin to see the slide.

Explanation / Answer

#Instead of using the inner loop to compute mean, we can simply use an inbuilt function as I have done below


length <- length(c(seq(10, 2010, 100)))
min <- 3
max <- 7
X <- as.integer(runif(2010,min,max+1) )

means <- rep(NA, length);
std <-rep(NA, length);

i=1;
for (n in seq(10, 2010, 100)) {
             means[i] <- mean(X[1:n]);
             std[i] <- sd(X[1:n]);
             print(c(means[i],std[i]));
             i<-i+1;

              # I would not recommend drawing the histogram evertime, just draw it after loop and see the result
             #hist(X[1:n], xlim=c(3.5,6.5),main=paste(n," Laws of large number"), breaks=seq(min,max,1));
             #hist(means,xlim=c(3.5,6.5), main=paste(1000010," Means "), breaks=seq(min,max, 1));
}

hist(X, xlim=c(3.5,6.5),main=paste(n," Laws of large number"), breaks=seq(min,max,1));hist(means,xlim=c(3.5,6.5), main=paste(2010," Means "), breaks=seq(min,max, 1));