Skip to content

Instantly share code, notes, and snippets.

@TeWu
Last active February 19, 2022 21:05
Show Gist options
  • Save TeWu/60ca98e9dff514023d3276eb6706702d to your computer and use it in GitHub Desktop.
Save TeWu/60ca98e9dff514023d3276eb6706702d to your computer and use it in GitHub Desktop.
R Student's t-Test
observations <- c(17.13, 17.71, 17.51, 19.39, 17.70, 19.15, 17.17, 18.48, 21.71, 19.55, 17.63, 18.55, 14.77)
tr <- t.test(observations, mu=18, conf.level=0.99)
tr # print Test Results
# Plot t-distribution
stderr <- sqrt(var(observations)/length(observations))
x <- seq(-4, 4, by=0.01)
y <- dt(x, df=tr$parameter)
plot(x, y, type='l')
abline(v=0, col="black")
abline(v=tr$statistic, col="blue") # t-statistic
abline(v=(tr$conf.int[1:2] - tr$null.value) / stderr, col="red") # confidance interval
# Plot normal distribution approximation
x <- seq(tr$estimate - 4 * stderr, tr$estimate + 4 * stderr, by=0.1)
y <- dnorm(x, mean=tr$estimate, sd=stderr)
plot(x, y, type='l', col="blue")
# polygon(c(min(x), x[x<tr$conf.int[1]], tr$conf.int[1], tr$conf.int[1]),
# c(0, y[x<tr$conf.int[1]], dnorm(tr$conf.int[1], mean=tr$estimate, sd=stderr), 0),
# col="pink")
# polygon(c(tr$conf.int[2], x[x>tr$conf.int[2]], max(x), tr$conf.int[2]),
# c(dnorm(tr$conf.int[2], mean=tr$estimate, sd=stderr), y[x>tr$conf.int[2]], 0, 0),
# col="pink")
abline(v=tr$null.value, col="black") # H0 mean
abline(v=tr$estimate, col="blue") # estimated mean
abline(v=tr$conf.int[1:2], col="red") # confidance interval - there is 99% probability the true mean is inside this interval

	One Sample t-test

data:  observations
t = 0.41662, df = 12, p-value = 0.6843
alternative hypothesis: true mean is not equal to 18
99 percent confidence interval:
 16.80671 19.57021
sample estimates:
mean of x
 18.18846

plot1 plot2 plot3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment