Lesson 91 – The One-Sample Hypothesis Tests in R

The last time we did something in R is in Lesson 83. Since then, we have been learning the hypothesis testing framework. In Lesson 84, we first made friends with the hypothesis tests — the concept of needing evidence beyond a reasonable doubt. In Lesson 85, we learned the framework — the elements of hypothesis testing that provide us with a systematic way of setting up the test and using data to verify the hypothesis.

In Lessons 86, 87, and 88, we learned the one-sample hypothesis test on proportion, mean, and the variance, respectively. Then, in Lesson 89, we learned the one-sample sign test as a complement to the one-sample hypothesis test on the mean, which can account for outliers as well. Last week (Lesson 90), we dived into the bootstrap-based method where we relaxed the assumptions on the null distribution. The bootstrap-based process provides us the flexibility to run the test on various statistics of interest.

Today, let’s pause and look at how to perform these hypothesis tests in R. Brace yourself for an R drive.

To help us with this lesson today, we will make use of the eight data points on 2003 Ford Focus vehicle mileage that Joe used in Lesson 89.

The Basic Steps

Step1: Get the data

You can get the data from here.

Step 2Create a new folder on your computer

Let us call this folder “lesson91”. 

Step 3Create a new code in R

Create a new code for this lesson. “File >> New >> R script”. Save the code in the same folder “lesson91” using the “save” button or by using “Ctrl+S”. Use .R as the extension — “lesson91_code.R”

Step 4Choose your working directory

“lesson91” is the folder where we stored the code. Use “setwd(“path”)” to set the path to this folder. Execute the line by clicking the “Run” button on the top right.

setwd("path to your folder")

Step 5Read the data into R workspace

Since the sample data is small enough, instead of saving the data in a text file and reading it into R workspace, we can directly input the data into the workspace as follows:

## Data Entry ##
# FORD MPG - reported # 
  x = c(21.7, 29, 28.1, 31.5, 24, 21.5, 28.7, 29)

The Baseline for Null Hypotheses

Let’s run the hypothesis tests on the mean, standard deviation, and the proportion. For this, we have to make some modest assumptions.

For the mean, we will use the EPA specified rating of 26.2 MPG. \mu = 26.2 MPG.

For comparing the standard deviation, we are unsure of the baseline standard deviation from the EPA rating. However, they provide us with a range that is between 22 MPG and 32 MPG. If we can assume that the range is covered by six standard deviations, i.e., 32 - 22 = 6 \sigma, we can get an estimate for baseline \sigma. In this case, \sigma = 1.67 MPG.

Further, let’s also assume that one in eight cars will usually have a mileage less than the minimum rating of 22 MPG. p = \frac{1}{8}

# Compare to Baseline
  mu = 26
 
  rangex = c(22,32)
  sigma = diff(range_ford)/6

  n = length(x)
  p = 1/n 

Hypothesis Test on the Mean

For the hypothesis test on the mean, we learned three methods, the t-test, the sign-test, and the bootstrap-based test.

Let’s start with the t-test. For the t-test, the null and the alternate hypothesis are:

H_{0}: \mu \ge 26.2 MPG

H_{A}: \mu < 26.2 MPG

The null distribution is a T-distribution with (n-1) degrees of freedom. The test statistic is t_{0}=\frac{\bar{x}-\mu}{\frac{s}{\sqrt{n}}}. We have to verify how likely it is to see a value as large as t_{0} in the null distribution. 

Let’s compute the test statistic.

#T-Test #
   xbar = mean(x)

   s = sd(x)

   to = (xbar-mu)/(s/sqrt(n))
> to
   [1] 0.5173082

The test statistic is 0.517.

For a selected rejection rate of \alpha we have to compute the p-value corresponding to this test statistic, or the critical value on the T-distribution.

   alpha = 0.05
   
   pvalue_ttest = pt(to,df=(n-1))   
   
   tcritical = qt(alpha,df=(n-1))
   

When you execute these lines, you will see that the p-value is 0.69, and the critical value from the t-distribution is -1.89. The “pt” function computed P(T \le t_{0}) from a T-distribution with user-specified degrees of freedom. For our case, df = 7. The “qt” function computes the quantile corresponding to a probability of 5%, i.e., \alpha=0.05 from a T-distribution with user-specified degrees of freedom.

> pvalue_ttest
   [1] 0.6895594

> tcritical
   [1] -1.894579 

Since the p-value is greater than 0.05, or since t_{0}>t_{critical}, we cannot reject the null hypothesis.

In R, there is a function to run this test — “t.test

We could have used the function directly on the sample data x.

# using t-Test function in R #
   t.test(x,alternative = "less", mu = mu, conf.level = 0.95)
One Sample t-test
 data:  x
 t = 0.51731, df = 7, p-value = 0.6896
 alternative hypothesis: true mean is less than 26
 95 percent confidence interval:
      -Inf 29.20539
 sample estimates:
 mean of x 
   26.6875 

It provides t_{0} and the p-value as the outputs from which we can decide on the null hypothesis.


Next, let’s look at how to conduct the sign-test in R. The null and the alternative hypothesis for the sign-test are

H_{0}: P(X > 26.2) = 0.5

H_{A}: P(X > 26.2) < 0.5

If H_{0} is true, about half of the values of sample X will be greater than 26.2 MPG, and about half of them will be negative. If H_{A} is true, more than half of the values of sample X will be less than 26.2 MPG, i.e., the sample shows low mileages — significantly less than 26.2 MPG.

To run this test, we should compute s^{+}, the test statistic that determines the number of values exceeding 26.2 MPG.

#Sign-Test
 splus = length(which(x>mu))
 > splus
   [1] 5 

s^{+} is 5.

Under the null hypothesis, s^{+} follows a binomial distribution with a probability of 0.5. Using this assumption, we compute the p-value using the “binomial.test” function in R.

# Using Binom Test function in R 
   binom.test(splus,n,p=0.5,alternative = "less")
Exact binomial test
 data:  splus and n
 number of successes = 5, number of trials = 8, p-value = 0.8555
 alternative hypothesis: true probability of success is less than 0.5
 95 percent confidence interval:
  0.0000000 0.8888873
 sample estimates:
 probability of success 
                  0.625 

The test provides the p-value, i.e., P(S^{+} \le 5) from a binomial distribution with n = 8 and p = 0.5.

P(S^{+} \le 5)=\sum_{k=0}^{k=5}{8 \choose k} p^{k}(1-p)^{8-k}=0.8555

Since the p-value is greater than 0.05, the rejection rate, we cannot reject the null hypothesis.


Lastly, we will check out the bootstrap-based test on the mean. For the bootstrap-based one-sided test, the null hypothesis and the alternate hypothesis are

H_{0}: P(\bar{x} > 26.2) = 0.5

H_{A}: P(\bar{x} > 26.2) < 0.5

Use the following lines to set up and run the test.

#Bootstrap Test
 N = 10000

 xmean_null = matrix(NA,nrow=N,ncol=1)
  for (i in 1:N)
   {
     xboot = sample(x,n,replace=T)
     xmean_null[i,1] = mean(xboot)
   }
 
hist(xmean_null,col="pink",xlab="Mean of the Distribution",font=2,font.lab=2,main="Null Distribution Assuming Ho is True")

points(mu,10,pch=15,cex=2,col="blue")

abline(v=c(quantile(xmean_null,0.95)),col="black",lwd=2,lty=2)

pvalue_bootstrap = length(which(xmean_null>mu))/N
> pvalue_bootstrap
   [1] 0.7159 

In the loop, we are executing the “sample” function to draw a bootstrap-replicate from the original data. Then, from this bootstrap-replicate, we compute the mean. Repeated such sampling and computation of the bootstrap-replicated mean statistic forms the null distribution. From this null distribution, we calculate the p-value, i.e., the proportion of the null distribution that exceeds the baseline of 26.2 MPG.

Since the p-value (0.716) is greater than a 5% rejection rate, we cannot reject the null hypothesis.

We can also observe that the code provides a way to visualize the null distribution and the basis value of 26.2 MPG. If the basis value \mu=26.2 is so far out on the null distribution of \bar{x} that less than 5% of the bootstrap-replicated test statistics are greater than \mu, we would have rejected the null hypothesis.

Hypothesis Test on the Variance

For the hypothesis test on the variance, we learned two methods, the Chi-square test, and the bootstrap-based test.

Let’s first look at the Chi-square test. The null and alternate hypothesis is as follows:

\sigma^{2}=1.67^{2}

\sigma^{2} \neq 1.67^{2}

The alternate hypothesis is two-sided. Deviation in either direction (less than or greater than) will reject the null hypothesis.

If you can recall from Lesson 88, \frac{(n-1)s^{2}}{\sigma^{2}} is our test statistic, \chi^{2}_{0}, which we will verify against a Chi-square distribution with (n-1) degrees of freedom.

# Chi-square Test
chi0 = ((n-1)*s^2)/sigma^2

pvalue_chi0 = pchisq(chi0,df=(n-1))

chilimit_right = qchisq(0.975,df=(n-1))

chilimit_left = qchisq(0.025,df=(n-1))

The “pchisq” function computes P(\chi^{2} \le \chi^{2}_{0}) from a Chi-square distribution with user-specified degrees of freedom, df = 7. The “qchisq” function computes the quantile corresponding to a specified rate of rejection. Since we are conducting a two-sided test, we calculate the limiting value on the left tail and the right tail.

 > pvalue_chi0
   [1] 0.9999914 

The p-value is 0.999. Since it is greater than 0.975, we reject the null hypothesis based on the two-sided test.

> chi0
   [1] 35.60715

> chilimit_left
   [1] 1.689869

> chilimit_right
   [1] 16.01276 

The lower and the upper bound from the null distribution are 1.69 and 16.01, respectively. Whereas, the test statistic \chi^{2}_{0} is 35.60, well beyond the upper bound acceptable value. Hence we reject the null hypothesis.


Now, let’s look at how to run a bootstrap-based test for the standard deviation. For the bootstrap-based two-sided test, the null hypothesis and the alternate hypothesis are

H_{0}: P(\sigma > 1.67) = 0.5

H_{A}: P(\sigma > 1.67) \neq 0.5

Use the following lines to set up and run the test.

# Bootstrap Test for Standard Deviation
 N = 10000
 
xsd_null = matrix(NA,nrow=N,ncol=1)
 for (i in 1:N)
   {
     xboot = sample(x,n,replace=T)
     xsd_null[i,1] = sd(xboot)
   }

hist(xsd_null,col="pink",xlab="Standard Deviation of the Distribution",font=2,font.lab=2,main="Null Distribution Assuming Ho is True")

points(sigma,10,pch=15,cex=2,col="blue")
   abline(v=c(quantile(xsd_null,0.025),quantile(xsd_null,0.975)),col="black",lwd=2,lty=2)

pvalue_bootstrap = length(which(xsd_null>sigma))/N
> pvalue_bootstrap
   [1] 0.9747 

As before, in the loop, we are executing the “sample” function to draw a bootstrap-replicate from the original data. Then, from this bootstrap-replicate, we compute the standard deviation. Repeated such sampling and computation of the bootstrap-replicated standard deviation statistic forms the null distribution for \sigma. From this null distribution, we calculate the p-value, i.e., the proportion of the null distribution that exceeds the baseline of 1.67 MPG.

Since the p-value (0.975) is greater than or equal to 0.975, (\frac{\alpha}{2} rejection rate), we reject the null hypothesis.

The code provides a way to visualize the null distribution and the basis value of 1.67 MPG. The basis value is far left on the null distribution. Almost 97.5% of the bootstrap-replicated test statistics are greater than \sigma = 1.67 — we reject the null hypothesis.

Hypothesis Test on the Proportion

For the hypothesis test on the proportion, we can employ the binomial distribution (parametric) as the null distribution, or use the bootstrap-based method (non-parametric) to generate the null distribution. For the parametric approach, the null and the alternative hypothesis are

H_{0}: p \le \frac{1}{8}

H_{A}: p > \frac{1}{8}

We are considering a one-sided alternative since the departure in one direction (greater than) is sufficient to reject the null hypothesis.

From a sample of eight cars, the null distribution is the probability distribution of observing any number of cars having a mileage of less than 22 MPG. In other words, out of the eight cars, we could have 0, 1, 2, 3, …, 8 cars to have a mileage less than 22 MPG, the lower bound specified by EPA.

The null distribution is the distribution of the probability of observing these outcomes. In a Binomial null distribution with n = 8 and p = 1/8, what is the probability of getting 0, 1, 2, …, 8? and if more than an acceptable number (as seen in the null distribution) is seen, we reject the null hypothesis.

We can generate and plot that null distribution in R using the following lines.

## Hypothesis Test on the Proportion
 
ncars = length(which(x<22))

plot(0:n,dbinom(0:n,n,prob=p),type="o",xlab="Number of cars with MPG less than the range",ylab="P(X=x)",font=2,font.lab=2)

x_at_alpha = qbinom(0.95,n,prop) # approx quantile for 5% rejection 

cord.x <- c(x_at_alpha,seq(x_at_alpha,n),x_at_alpha) 

cord.y <- c(0, dbinom(x_at_alpha:n,n,prob=p), 0) 

polygon(cord.x,cord.y,col="pink")

points(ncars,0.002,pch=15,col="blue",cex=2)

pval = sum(dbinom(ncars:n,n,prob=p))

In the first line, we are computing the number of cars that have a mileage of less than 22 MPG, which is the test statistic. We observe this to be two cars.

> ncars
   [1] 2 

In the next few lines, we are plotting the null distribution as computed from a binomial distribution with n = 8 and p = 1/8, and visually showing the region of rejection using the “polygon” function.

Then, we compute the p-value as the probability of observing two or more cars having a mileage less than 22 MPG.

P(Y \ge 2) = \sum_{k=2}^{k=8} {8 \choose k} p^{k}(1-p)^{8-k}=0.2636

> pval
   [1] 0.2636952 

Since the p-value is greater than 0.05, we cannot reject the null hypothesis (based on the limited sample) that one in eight cars (2003 Ford Focus) will have a mileage of less than 22 MPG.


Let’s wrap up the day by running the bootstrap test on the proportion. For the bootstrap-based hypothesis test on the proportion, the null and the alternate hypothesis are

H_{0}: P(p > \frac{1}{8}) = 0.5

H_{A}: P(p > \frac{1}{8}) > 0.5

If we get a large proportion of the null distribution to be greater than 1/8, we will reject the null hypothesis.

Use the following lines to execute the test.

# Bootstrap Test on Proportion 
 N = 10000

xprop_null = matrix(NA,nrow=N,ncol=1)
 for (i in 1:N)
   {
     xboot = sample(x,n,replace=T)
     xprop_null[i,1] = length(which(xboot<22))/n
   }

hist(xprop_null,col="pink",xlab="Proportion of the Distribution",font=2,font.lab=2,main="Null Distribution Assuming Ho is True")

points(prop,10,pch=15,cex=2,col="blue")

abline(v=c(quantile(xprop_null,0.95)),col="black",lwd=2,lty=2)

pval=length(which(xprop_null>prop))/N
> pval
   [1] 0.631 

We are executing the “sample” function N = 10,000 times to draw bootstrap-replicates from the original data. Then, for each bootstrap-replicate, we compute the proportion that is less than 22 MPG. The 10,000 bootstrap-replicated proportions forms the null distribution for p. From this null distribution, we calculate the p-value, i.e., the proportion of the null distribution that exceeds the baseline of \frac{1}{8}

Since the p-value (0.631) is less than 0.95, (1-\alpha rejection rate), we cannot reject the null hypothesis. 63% of the bootstrap-replicated proportion is greater than the baseline. If more than 95% of the bootstrap-replicated proportion is greater than the baseline, we would have rejected the null hypothesis. This scenario would have unfolded if the original sample had several cars with less than a mileage of 22 MPG. The bootstrap replicates would show them, in which case the proportion would be much greater than 1/8 in many replicates, and overall, the p-value would exceed 0.95.

Take the next two weeks to digest all the one-sample hypothesis tests, including how to execute the tests in R. In two weeks, we will move on to the two-sample hypothesis tests.

Here is the full code for today’s lesson.

If you find this useful, please like, share and subscribe.
You can also follow me on Twitter @realDevineni for updates on new lessons.

Lesson 89 – The One-Sample Sign Test

Hypothesis Tests – Part IV

H_{0}: P(X > \mu) = 0.5

H_{A}: P(X > \mu) > 0.5

H_{A}: P(X > \mu) < 0.5

H_{A}: P(X > \mu) \neq 0.5

Joe is ready to buy his first (used) car as anyone does when they are new to the whole driving experience.

After a careful search on craigslist, he narrowed down to check out a 2003 Ford Focus and a 2011 Hyundai Sonata Hybrid. He liked their specs and wanted to verify the all-important gas mileage.

While he is taking the words of the owners at face value, he also wants to check the mileage reported by the general public to the EPA.

In case you are unaware, the United States Environmental Protection Agency (USEPA) maintains a website www.fueleconomy.gov where they provide information on the fuel economy for different vehicles.
They give their rating based on standardized tests to reflect typical driving conditions and driver behavior. The public also shares their miles per gallon (MPG) estimates.

At any rate, Joe navigated through this interesting website and checked out the data that people shared for these two varieties.

Here is the data shared by eight people for the 2003 Ford Focus.

As you can see, EPA rates an average of 26 MPG for this variety.

Joe wants to check if the average mileage for this car as derived from a sample data conforms to the EPA rating or not.

Joe already knows how to do this using the one-sample t-test. So he goes about establishing the null and the alternative hypothesis, deciding on the acceptable rejection rate, computing the test statistic and its corresponding p-value.

Here is a summary of his test.

From the sample of eight vehicles, he computed \bar{x} as 26.69 MPG, which he compares with EPA’s rating — \mu of 26 MPG. The test statistic t_{0} is 0.52.

His alternate hypothesis is \mu < 26 MPG against the null hypothesis of \mu \ge 26 MPG. So, the critical value from the T-distribution with 7 degrees of freedom (n=8) is -1.9.

Since the test statistic is greater than the critical value, he cannot reject the hypothesis.

Until further evidence is available, he will continue to believe that the 2003 Ford Focus will have an average fuel economy of 26 MPG.


Enter the Sign Test

Joe can also perform a One-Sample Sign Test if he needs more confirmation.

The sign test determines whether a given sample X is generally larger or smaller or different than a selected value \mu. It works well when there are outliers in the data.

Joe has to establish the following null hypothesis.

H_{0}: P(X > 26) = 0.5

If H_{0} is true, about half of the values of sample X will be greater than 26 MPG, and about half of them will be less than 26 MPG. In other words, the sample data will be dispersed around \mu with equal likelihood.

To this null hypothesis, he will cast an alternate hypothesis

H_{A}: P(X > 26) < 0.5

If H_{A} is true, more than half of the values of sample X will be less than 26 MPG. In other words, the sample shows low mileages — significantly less than 26 MPG.

Look at this visual. Joe is plotting the sample data on the number line and indicating 26 MPG cutoff line along with whether the sample data is greater than 26 MPG or less than 26 MPG using a plus and a minus sign — the sign test 😉

Three vehicles from the sample had a reported mileage of less than 26 MPG. Out of the eight data points, the number of positives is five, and the number of negative is three.

The number of positives, S^{+}, is the test statistic for the sign test.

In a sample of eight (n = 8), S^{+}=5.

S^{+} could have been 0, 1, 2, 3, 4, 5, 6, 7, or 8.

Under the null hypothesis, S^{+} follows a binomial distribution with a probability of 0.5. We consider this as the null distribution.

Look at this visual.

It shows the possible S^{+} values on the x-axis and P(S^{+}=k) on the y-axis. The null distribution is the distribution of the probability that S^{+} can be 0, 1, 2, …, or 8. For n = 8 and p = 0.5.

P(S^{+}=k) = {8 \choose k} p^{k}(1-p)^{8-k}

For instance, P(S^{+}=0) = {8 \choose 0} p^{0}(1-p)^{8-0} = 0.0039

Here is the full binomial table.

Now, since the sample yields S^{+}=5, p-value for this test is the probability of finding up to five positives — P(S^{+} \le 5).

P(S^{+} \le 5)=\sum_{x=0}^{x=5} {8 \choose x} p^{x}(1-p)^{8-x}=0.8555

Since the p-value is greater than 0.05, the rejection rate Joe has decided upon; he cannot reject the null hypothesis.

If you noticed, the sign test only uses the signs of the data and not the magnitudes. So it is resistant to outliers.


What about Hyundai Sonata Hybrid

Joe quickly looks for some data on the 2011 Hyundai Sonata Hybrid. Sure enough, he finds this.

There is a sample of 24 vehicles of this type, and EPA rates this at 36 MPG.

Let’s see how Joe uses the sign test to verify if the sample data conforms to the EPA specified rating.

He first establishes the null and the alternative hypothesis.

H_{0}: P(X > 36) = 0.5

H_{A}: P(X > 36) < 0.5

If H_{0} is true, about half of the 24 values found in the sample will be greater than 36 MPG, and about half of them will be negative.

If H_{A} is true, more than half of the 24 values will be less than 36 MPG. In other words, the sample reveals a significantly lower mileage than the EPA rated 36 MPG.

Joe then plots the data on the number line to visually find the number of positive and negative signs.

He counts them as 7.

There is one number that is exactly 36 MPG. He removes this from the sample and conducts the test with 23 data points.

The test statistic is S^{+}=7 out of 23 values (n = 23). The p-value for the test is then the probability of seeing value for S^{+} of up to 7 in a binomial distribution with n = 23 and p = 0.5.

P(S^{+} \le 7)=\sum_{x=0}^{x=7} {23 \choose x} p^{x}(1-p)^{23-x}=0.046

Since the p-value is less than \alpha, Joe has to reject the null hypothesis that the average mileage for the 2011 Hyundai Sonata Hybrid is 36 MPG.

Why can’t Joe just conduct the t-test?

He can. Here is the result of the t-test.

The test statistic t_{0} falls in the rejection region, i.e., t_{0}<t_{critical}, or the p-value is less than \alpha.

He will reject the null hypothesis test.

What about the outliers?

Suppose there is an error in entering the 21st value. Let’s say it is 48.8 MPG instead of 38.8 MPG.

How will this change the result of the t-test?

\bar{x} and s will be 33.875 MPG and 6.099 MPG respectively.

The test statistic t_{0} will be -1.706.

At 5% rejection rate and 23 degrees of freedom, t_{critical} will be -1.713.

Since t_{0}>t_{critical}, Joe would not be able to reject the null hypothesis.

Whereas, if he uses the sign test for his investigation, as he is doing now, the outlier data point 48.8 MPG will still show up only as a positive sign and the resultant S^{+} will still be seven and the p-value P(S^{+} \le 7) will still be 0.046.

The sign test is resistant to outliers.

If you find this useful, please like, share and subscribe.
You can also follow me on Twitter @realDevineni for updates on new lessons.

error

Enjoy this blog? Please spread the word :)