R
Beginner
1 min read
Descriptive Statistics and Hypothesis Tests
Example
# Descriptive statistics
x <- c(23, 45, 12, 67, 34, 56, 78, 29, 41, 55)
mean(x) # 44.0
median(x) # 43.0
sd(x) # 20.6
var(x) # 423.8
range(x) # 12 78
IQR(x) # interquartile range
quantile(x, probs = c(0.25, 0.5, 0.75))
summary(x) # min, Q1, median, mean, Q3, max
# Correlation matrix
data(mtcars)
cor(mtcars[ , c("mpg","hp","wt","qsec")])
round(cor(mtcars), 2) # full correlation matrix
# One-sample t-test (is mean different from 40?)
t.test(x, mu = 40)
# Two-sample independent t-test
group_a <- c(23, 34, 28, 31, 25)
group_b <- c(45, 52, 38, 49, 43)
result <- t.test(group_a, group_b, var.equal = FALSE)
result$p.value # p-value
result$conf.int # 95% confidence interval for mean difference
# Paired t-test
before <- c(140, 152, 148, 135, 160)
after <- c(130, 145, 140, 128, 152)
t.test(before, after, paired = TRUE)
# Chi-square test of independence
survey <- table(
gender = c("M","F","M","F","M","F","M","F"),
pref = c("A","A","B","B","A","B","B","A")
)
chisq.test(survey)
# Shapiro-Wilk normality test
shapiro.test(x)
# Wilcoxon rank-sum (non-parametric alternative to t-test)
wilcox.test(group_a, group_b)