doneonex write an R function to demonstrate simply the idea of the Central Limit Theorem. You can choose any underlying distribution (except the Normal) for which you know how to calculate the theoretical mean and SD. Your function should: 1. have an argument n for the sample size set to a suitable default value; 2. generate 1000 independent samples of size n from your chosen distribution, and display a histogram of the sample values; 3. superimpose on your histogram the Normal distribution density curve with the appropriate mean and standard deviation. You should run your function for a variety of different n's such as n = 5, 10, 20, 30 請問我這樣做對不對? CODE: z=NULL # sample size n n = 30 # Set up a vector of NAs of length no.samples # sample.means <- rep(NA,length = 1000) # # Generate 1000 independent samples of size n from binomial distribution # for(i in 1:1000) { binom.sample = rbinom(n,1,0.5) # # Store the sample mean # sample.means = mean(binom.sample) z=c(z, (sample.means-0.5)/sqrt(0.25/n)) } hist(z,freq=FALSE,prob=T) curve(dnorm(x,0,1),add=T)
Ihavenothing 可以不需要使用循环。例如你可以生成一个1000行n列的矩阵,然后对矩阵求每一行的均值,就得到你需要的sample.means向量。 m=matrix(rbinom(1000*n,1,0.5),1000,n); <br /> sample.means=rowMeans(m);