Thursday, April 7, 2016

Lab III

We will do two experiments today. The first one is to explore the distribution of one-sample T-statistics. The second one is to compare the power of two-sample independent T-test and Paired T-test.


1. A Numerical experiment to find out the distribution of one-sample T-statistics


First, let us write a function to compute one sample T-statistics

t.stat <- function(x){ # x is the input
  n <- length(x)
  tstat <-  mean(x)/sqrt(var(x)/n)
  return(tstat) # t is the result you get after applying this function
}

Now, you have created a function that computes one sample t-statistic.


Next we will simulate 10000 set of random sample of size 10, and compute t-statistics

tt <- rep(0,10000)
for(i in 1:10000){
  x <- rnorm(10)
  tt[i] <- t.stat(x)
}

hist(tt) # histogram is not the best tool to tell the difference between t-distribution and normal distribution

qqnorm(tt) # a better tool is quantile-quantile plot
abline(0,1) # if two distribution are similar, all points should roughly lineup on the line x=y

qqplot(qt((1:10000)/10001,df=9),tt) # compare quantile of t-distribution with df=9 with the t-statistics
abline(0,1)


2. A numerical experiment to compare the power of paired t-test and two sample independent T-test. 

t.paired <- rep(0,10000)
t.ind <- rep(0,10000)


for(i in 1:10000){
   
   
   y1 <- rnorm(10) #  simulate the first one observation of a pair
   d <- rnorm(10,1,1) # the difference between two observations in a pair follows a normal distribution with mean 1. 
   y2 <- y1+d # simulate the second observation in the pair

   t.paired[i] <- t.stat(d) # paired t-test
   t.ind[i] <- t.test(y1,y2,var.equal=T)$stat # treat it as two independent sample
}

sum(abs(t.paired) > qt(1-0.025,9)) # the number of times the observed t-statistics exceed the threshold of P-value less that 0.05

sum(abs(t.ind) > qt(1-0.025,18)) # check the power of two-sample independent test



If the data follows a paired design, which of the two statistical tests are better, two-sample independent t-test, or paired t-test?


Now, try to do the following experiment on your own, if two samples are independent, and we applied paired t-test to it, what is the consequence?

t.paired <- rep(0,10000)
t.ind <- rep(0,10000)


for(i in 1:10000){
   
   y1 <- rnorm(10) # the first sample of 10 from standard normal
   y2 <- rnorm(10,1,1) # the second sample of 10 at mean 0 and std 1

   d <-       # fill the blank here

   t.paired[i] <- t.stat(d) # paired t-test
   t.ind[i] <- t.test(y1,y2,var.equal=T)$stat # treat it as two independent sample
}

sum(abs(t.paired) > qt(1-0.025,9)) # the number of times the observed t-statistics exceed the threshold of P-value less that 0.05

sum(abs(t.ind) > qt(1-0.025,18)) # check the power of two-sample independent test


For the two-independent T-test above, we used the version with  the assumption that the variances of two groups are equal, and we simulated the data following exactly this assumption. Below we would like to experiment what might happen if we use the same method when the assumption is not true. We will also do the t-test without the equal variance assumption to see if it works well.

p.eq <- rep(0,10000)
p.neq <- rep(0,10000)
for(i in 1:10000){
   
## we generate the data under the null hypothesis that mu1 = mu2

   y1 <- rnorm(10) # the first sample of 10 from standard normal

   y2 <- rnorm(10,0,10) # the second sample of 10 at mean 0 and std 10



   p.eq[i] <- t.test(y1,y2,var.equal=T)$p.value # get p-value from the t-test that assumes the equal variance
   p.neq[i] <- t.test(y1,y2,var.equal=T)$p.value # P-value of the t-test that does not assumes the equal variance
} ## end of the loop


sum(p.eq < 0.05) # see how many times we get P-value less than 0.05 

If we get P-values less than 0.05 more often than the specified 0.05 significance level, then we have a problem of inflated Type-I error. We want to control Type-I error at 5% but using this method we will get more. 

sum(p.neq < 0.05) # see how many times we get P-value less than 0.05




Lab II

Lab II

A numerical experiment on CLT

Recall Central Limit Theorem

Let $X_1 ,X_2 ,…,X_n$ be an independent random sample of size n from a distribution (which may or may not be normal) with mean $\mu$ and standard deviation $\sigma$.

1. If sample size (n) is large enough, the distribution of sample mean $\bar{X}$ is approximately a normal distribution
2. And the mean and standard deviation of the sample means are $\mu$ and $\sigma / \sqrt{n}$


We will now do a numerical experiments to check if the CLT is true. The first three steps are exactly the same as we did in Lab I, when we took a look at the mean and variance of the distribution of sample mean. A last step is added so we can see (literally) if the distribution is approximately normal.
1. Take a random sample of 100 from a distribution, compute the sample mean
2. Repeat it 10000 times
3. computer the mean and standard deviation of the sample means
4. Draw a histogram of the sample means

Based on central limit theorem, the sampling distribution of the sample means should be close to a Normal distribution with  mean at 0 and the standard variation of of 1/10.


First, we will take random samples of 100 from a standard normal distribution 

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rnorm(100) # take a random sample of 100 from a standard normal distribution
   xbar[i] <- mean(x)
}

mean(xbar)
sqrt(var(xbar))
hist(xbar)

The best way to visualize if data fits a certain distribution is Quantile-Quantile plot, on which we will discuss more later. R function qqnorm let you compare your data with a normal distribution. If you see a straight line, the data is approximately normal.

qqnorm(xbar)


Now let take a sample of 100 from a Poisson distribution with $\lambda =1$. The Poisson distribution is very useful in modeling the rare events and the parameter $\lambda$ is both its mean and variance. 

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rpois(100,1) # take a random sample of 100 from a Poisson distribution with its parameter lambda=1
   xbar[i] <- mean(x)
}


mean(xbar)
sqrt(var(xbar))
hist(xbar)


Finally let's take a sample of 100 from a binomial distribution with $p=0.05$.

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rbinom(100,size=1,prob=0.05) # take a random sample of 100 from a Bernoulli trial, aka, binomial of size 1. 
   xbar[i] <- mean(x)
}

mean(xbar)
sqrt(var(xbar))
hist(xbar)

Does the sampling distribution look like a Normal distribution? Is CLT wrong?

In Lab exercise:

Now I will ask you to lead an investigation to find out what sample size is considered "large enough" for the sampling distribution of the sample mean (of Bernoulli trials with p=0.05) being approximately normally distributed. Does such sample size also work for Bernoulli trials with p=0.01.


Wednesday, April 6, 2016

Introduction to R Programming

What we will do in this lab

1. Introduce basic programming in R
2. Use R to perform statistical simulations that illustrates the basic idea of sampling distribution, and the Central Limit Theorem.
3. Illustrate the power of statistical simulation by finding out the sampling distribution of the one sample T-statistics.

Coding and Debugging

Coding/Programming is simply writing a set of instructions or commands to a computer, and the computer will faithful follow those instructions.

However, in reality, getting a set of code to work as you intend to could be quite frustrating sometimes. Rarely any program works the very first time, and it almost always requires a lot of patience to debug. A program works correctly only if
1, the instructions are understood by the computer;
2. the instructions constructed together perform their intended task.

For the first part, the computer usually lets you know which of your instructions it does not understand, so that you will have some idea on which command needs to be fixed. Getting the second part correct is much trickier, especially for a long code. A good planning helps a lot, and a good writing style helps a lot too. Essentially, you want to structure your program in a way that you can track the problem to smaller components and to fix it. A very useful technique is to look at what was produced at each step, and it is very easy to do it in R.

I expect that you all have learned a few things about R already and know
1. how to use it as a calculator and call a function to do certain things, for example, t-test
2. how to input data to a R object
3. how to save a R workspace


Use for loop to do repetitive tasks

Let us start with something simple. We will create a random sample from a standard normal distribution, and plot a histogram.

x <- rnorm(1000) # random sample from a standard normal distr
hist(x) # draw a histogram

Now, I want to observe the effect of the number of bins, I draw the histograms of the same data using different number of bins.

hist(x, breaks=3)
hist(x, breaks=10)
hist(x, breaks=25)
hist(x, breaks=50)

Now, I want to put all 4 histograms in a single panel

par(mfrow=c(2,2)) # divide the drawing panel into 2x2
hist(x, breaks=3)
hist(x, breaks=10)
hist(x, breaks=25)
hist(x, breaks=50)

Alternatively, if I don't want to copy and paste hist(x,breaks=?) 3 times, I can use a for loop to draw 4 histograms, each time with a different number of bins. 

for(nb in c(3,10, 25, 50)){
   hist(x,breaks=nb) 
} 
# repeat the command(s) in the brackets 4 times
# each with a different nb


Mean and Variance of Sample Mean

Let $X_1 ,X_2 ,…,X_n$ be an independent random sample of size n from a distribution (which may or may not be normal) with mean $\mu$ and standard deviation $\sigma$.

We already learned that sample mean $\bar{X}$ has mean $\mu$ and variance $\sigma^2 /n$

We will now do two numerical experiments to check if this is true.

First, we will take a random samples of 100 from a standard normal distribution with $\mu=0$ and $\sigma^2=1$, $E(\bar{X})=0$ and $Var(\bar{X})=1/100=0.01$.

To do this experiment, we will
1. Take a random sample of 100 from a distribution, compute the sample mean
2. Repeat it 10000 times and keep 10000 sample means computed each time
3. computer the mean and the variance of the sample means


xbar <- rep(0,10000) # create a vector to store 1000 sample means

for(i in 1:10000){
   x <- rnorm(100) # take a random sample of 100 from a standard normal distribution
   xbar[i] <- mean(x)
}

Now, compute the mean and variance of the sample means to see if they are close to the theoretical value.

mean(xbar)  # the theoretical value should be 0
var(xbar)   # the theoretical value should be 1/100


Now let's take a sample of 100 from a Bernoulli trial with $p=0.05$. The mean of a Bernoulli trial is $p=0.05$ and the variance is $p(1-p)=0.05\times 0.95=0.0475$.

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rbinom(100,size=1,prob=0.05) # take a random sample of 100 from a Bernoulli trial, aka, binomial of size 1. 
   # x should be a vector of 0's and 1's 
   xbar[i] <- mean(x)
}

mean(xbar) # the theoretical value should be 0.05
var(xbar) # the theoretical value should be 0.0475/100

In Lab Exercise:

 1. Take a sample of 4 from a Bernoulli trial with $p=0.05$. What is the theoretical value of the mean and variance of the sample mean? Verify it with a simulation.


2. Take sample of 25 from a Poisson distribution with parameter $\lambda=2$. What is the theoretical value of the mean and variance of the sample mean? Verify it with a simulation. (Use function rpois to draw random number from a Poisson distribution).


A numerical experiment on CLT

Recall Central Limit Theorem

Let $X_1 ,X_2 ,…,X_n$ be an independent random sample of size n from a distribution (which may or may not be normal) with mean $\mu$ and standard deviation $\sigma$.

1. If sample size (n) is large enough, the distribution of sample mean $\bar{X}$ is approximately a normal distribution
2. And the mean and standard deviation of the sample means are $\mu$ and $\sigma / \sqrt{n}$


We will now do a numerical experiments to check if the CLT is true. The first three steps are exactly the same as we did in Lab I, when we took a look at the mean and variance of the distribution of sample mean. A last step is added so we can see (literally) if the distribution is approximately normal.
1. Take a random sample of 100 from a distribution, compute the sample mean
2. Repeat it 10000 times
3. computer the mean and standard deviation of the sample means
4. Draw a histogram of the sample means

Based on central limit theorem, the sampling distribution of the sample means should be close to a Normal distribution with  mean at 0 and the standard variation of of 1/10.


First, we will take random samples of 100 from a standard normal distribution 

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rnorm(100) # take a random sample of 100 from a standard normal distribution
   xbar[i] <- mean(x)
}

mean(xbar)
sqrt(var(xbar))
hist(xbar)

The best way to visualize if data fits a certain distribution is Quantile-Quantile plot, on which we will discuss more later. R function qqnorm let you compare your data with a normal distribution. If you see a straight line, the data is approximately normal.

qqnorm(xbar)


Now let take a sample of 100 from a Poisson distribution with $\lambda =1$. The Poisson distribution is very useful in modeling the rare events and the parameter $\lambda$ is both its mean and variance. 

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rpois(100,1) # take a random sample of 100 from a Poisson distribution with its parameter lambda=1
   xbar[i] <- mean(x)
}


mean(xbar)
sqrt(var(xbar))
hist(xbar)

Finally let's take a sample of 100 from a binomial distribution with $p=0.05$.

xbar <- rep(0,10000) # create a vector to store the sample means

for(i in 1:10000){
   x <- rbinom(100,size=1,prob=0.05) # take a random sample of 100 from a Bernoulli trial, aka, binomial of size 1. 
   xbar[i] <- mean(x)
}

mean(xbar)
sqrt(var(xbar))
hist(xbar)

Does the sampling distribution look like a Normal distribution? Is CLT wrong?

In Lab exercise:

Now I will ask you to lead an investigation to find out what sample size is considered "large enough" for the sampling distribution of the sample mean (of Bernoulli trials with p=0.05) being approximately normally distributed. Does such sample size also work for Bernoulli trials with p=0.01.