SyntaxStudy
Sign Up
R Descriptive Statistics and Hypothesis Tests
R Beginner 1 min read

Descriptive Statistics and Hypothesis Tests

R was born as a statistical computing language, so descriptive and inferential statistics are first-class citizens. Base R provides a comprehensive set of functions for descriptive statistics: mean(), median(), sd() (standard deviation), var() (variance), skewness and kurtosis via the moments package, and cor() / cov() for correlation and covariance matrices. The summary() function gives a five-number summary plus mean for numeric variables, while table() and prop.table() compute frequency and relative-frequency distributions for categorical variables. Hypothesis testing functions in base R follow a consistent pattern: the function accepts vectors of observations, returns an object of class htest, and you call print() or extract components like the p-value with $p.value. t.test() performs one-sample, two-sample independent, and paired t-tests depending on the arguments. prop.test() tests proportions; binom.test() performs an exact binomial test. All return a confidence interval along with the test statistic and p-value. The chi-square test via chisq.test() assesses independence between two categorical variables given a contingency table (from table()). Fisher's exact test (fisher.test()) is the appropriate alternative when cell counts are small. The Shapiro-Wilk test for normality (shapiro.test()) and Kolmogorov-Smirnov test (ks.test()) check distributional assumptions. Non-parametric alternatives like the Wilcoxon rank-sum test (wilcox.test()) and Kruskal-Wallis test (kruskal.test()) are used when normality cannot be assumed.
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)