Write a simulation in R that shows the distribution of the t-‐test statistic for a two-‐sample t test when the null hypothesis is true (i.e. when H0: µ1 -‐ µ2 = 0 is true). To do this, you should use a for loop that repeatedly performs t-‐tests comparing sample means of data that come from distributions with the same population mean and standard deviation. Use rnorm() to take samples, t.test() to perform the t-‐ tests, and use “$statistic” to extract the t-‐test statistic from the t.test() procedure (e.g. t.test(x,y)$statistic). Make a histogram of the test statistics.
R code with comments (all statements starting with # are comments and can be removed)
#set the random seed
set.seed(123)
#set the mean of the 2 populations
mu<-10
#set the standard deviation of 2 populations
sigma<-5
#set the number of simulations
R<-1000
#set the sample size
n<-20
#initialize the variable to hold the test statistics
tstat<-numeric(R)
#loop R times
for (i in 1:R){
#draw a sample of size n
s1<-rnorm(n,mu,sigma)
#draw a second sample of size n
s2<-rnorm(n,mu,sigma)
#store the statistics part of the t test
tstat[i]<-t.test(s1,s2)$statistic
}
#Make a histogram
hist(tstat,main="Histogram of t-test statistic",xlab="t
stat")
# get this
Get Answers For Free
Most questions answered within 1 hours.