sequence = 1:5 for( val in sequence) { print(val) } ## Here val is the value ## and c(0.25,1.8,9.75,10000) is the sequence sequence = c(0.25,1.8,9.75,10000) for( val in sequence) { print(val) } ## Here k is the value ## and 1:5 is the sequence for( k in 1:5) { print(k) } ## Here k is the value ## and 1:3 is the sequence N = c(10,20,30) for (k in 1:length(N)) { n = N[k] print(n) } ## Here n is the value ## and c(10,20,30) is the sequence N = c(10,20,30) for (n in N) { print(n) } ############################################################ N = 20 n = 5 ## Randomly Generate the N cluster means ## using N(0,1) distribution, and sorting ## them in ascending order. N.draws = rnorm(N) MUs = sort(N.draws) ## Generate the matrix Y, which is a ## single realization of the scenario #- Step 1: Generate a matrix Z (N rows by n columns) #- of iid N(0,1) realizations Z = array(rnorm(N*n), c(N,n)) #- Step 2: Form a matrix M (N rows by n columns) #- with row i having all entries equal to MUs[i] M = array(MUs, c(N,n)) #- Step 3: Now we have that Y = Z+M, will generate #- a single realization of matrix Y with row i #- being iid draws from N(MUs[i], 1) Y = Z + M ## Y is now ready to be used sample.means = sort(apply(Y,1, mean)) ## Put the two column vectors into an N by 2 matrix SP: SP = cbind(sample.means, MUs) ## View the results (Sample Mean, Population Mean) SP ################################################################## N = 20 n = 5 reps = 1e3 squared.diff = array(0,N) for ( r in 1:reps) { ## Generate the population means for this ## replication N.draws = rnorm(N) MUs = sort(N.draws) ## Generate a single realization of Y ....paste code from above ## Compute the ordered sample means of Y ....paste code from above ## Compute the Squared Difference Vector, ## and add it to the vectors computed before squared.diff = squared.diff + (sample.means - MUs)^2 } ## Divide the sum of the squared difference vector ## by the number of vectors in the sum (which is reps) MSE.vec = squared.diff/reps ########################################################### n=100 ## Generate n realizations X=rgeom(n,prob=0.25) ## Set the starting value oldTheta = 0.6 ## Let k count the number of itterations k=0 distance = Inf while( distance >= 1e-6 ) { k=k+1 Lprime = n/oldTheta - (sum(X) - n)/(1-oldTheta) Lprimeprime = -n*oldTheta^(-2) - (sum(X)-n)*(1-oldTheta)^(-2) ## Newton's Step newTheta = oldTheta - Lprime/Lprimeprime ## Compute distance we just stepped distance = abs(newTheta-oldTheta) ## Update oldTheta for the next iteration oldTheta = newTheta ## Print our progress cat("k=",k,"newTheta=",newTheta,"Distance=",distance,"\n") } MLE = newTheta