# One Sample t-test in R

The following is the core R syntax to do one sample t-test in R. In particular, Method 1 uses built-in R function, whereas method 2 writes the function to test one sample t-test in R from scratch.

Method 1:

t.test(vector_name, mu = value_to_compare, alternative = “two.sided”)

Method 2:

(mean(vector_name)-value_to_compare)/(sd(vector_name)/sqrt(number_of_observation))

## Data Example for One Sample t-test

Suppose that you would like to see whether a group of students’ exam grade mean is significantly different from 60, a predetermined number. The following is the grades of these students.

65, 70, 75, 80, 68, 95

The null and alternative hypotheses for one sample t-test are as follows.

• H0: The mean is equal to 60.
• Ha: The mean is unequal to 60

## Example for Method 1

The following uses the function of t.test() to do the one sample t-test in R. It first reads the data and then use the function. Note that, typically, we use two sided hypothesis testing.

``````# sample data
exam_data<-c(65,70,75,80,68,95)

# use t.test() to do one sample t-test in R
t.test(exam_data, mu = 60, alternative = "two.sided")``````

The following is the output. As we can see that the p-value is smaller than 0.05. Thus, we can conclude that we can reject the null hypothesis. Further, based on the mean, we can see that the mean of 75.5 is significantly higher than 60.

```	One Sample t-test

data:  exam_data
t = 3.4731, df = 5, p-value = 0.01779
alternative hypothesis: true mean is not equal to 60
95 percent confidence interval:
64.02798 86.97202
sample estimates:
mean of x
75.5 ```

## Example for Method 2

We can also write R code from scratch to do one sample t-test analysis. The following is the formula for one-sample t-test.

In the formula of one-sample t-test, the numerator is the mean of the sample minus the predetermined value to compare with (i.e., μ). S is the sample standard deviation and n is the sample size.

The following is the complete R code, including the data sample as well as the complete R code writing out the one-sample t-test formula.

``````# sample data
exam_data<-c(65,70,75,80,68,95)

# one sample t-test formula from scratch
(mean(exam_data)-60)/(sd(exam_data)/sqrt(6))``````

The following is the output. It only generates the t statistic, which is 3.47. Thus, we can see that it has the same result as in Example 1.

` 3.473149`