## Week 1: Estimators ## Code from class ## Monte Carlo Example # define a function for the sample variance sv <- function(y) { length(y) / (length(y)-1) * mean(y)^2 } # create a loop to compute and store 1,000 simuated sample variances # this will be from 50 random y values result <- numeric(500) for (i in 1:500) { result[i] <- sv(rnorm(50)) } # plot the result, after sorting the computed sample variances plot(sort(result), type="l", ylab="Computed sample variance") # now check whether sampling distribution matches a Chi^2 chisq.test(result) ## Birthday problem analysis lbdp <- function(n) { 1 - exp(lfactorial(365) - lfactorial(365-n) - n*log(365)) } x <- 1:60 plot(x,lbdp(x)) plot(x,lbdp(x), xlab="Number of people",ylab="Probability of same birthday") abline(h=.5, lty="dashed", col="red")