In: Computer Science
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.
code
solution
#output
#copyable code
#R code
#user set the random seed values
set.seed(123)
#set the mean value by using 2 populations
mu_val<-10
#standard deviation by using 2 populations
sigma_val<-4
#set the number
D<-900
#set the size
num<-20
#initialize the variable by using the statistics process
tstat<-numeric(D)
#using for loop
for (k in 1:D){
#draw a sample using rnorm
sample1<-rnorm(num,mu_val,sigma_val)
#draw a another sample
sample2<-rnorm(num,mu_val,sigma_val)
#store t.test statistics
tstat[k]<-t.test(sample1,sample2)$statistic
}
#draw histogram
hist(tstat,main="Histogram of t-test statistic",xlab="t stat")