Skip to content
R

Statistics

Compute summaries, run t-tests, linear models, ANOVA, and use distributions.

By EZ4Code Team
statisticstest

Code

set.seed(42)
x <- rnorm(100, mean = 5, sd = 2)
y <- 2 * x + rnorm(100, sd = 1)

# Summary statistics
print(mean(x))
print(median(x))
print(sd(x))
print(var(x))
print(quantile(x, c(0.25, 0.5, 0.75)))

# Correlation
print(cor(x, y))
print(cor.test(x, y))

# t-test
print(t.test(x, mu = 5))

# Linear regression
fit <- lm(y ~ x)
print(summary(fit))
print(coef(fit))
print(confint(fit))

# Predictions
newx <- data.frame(x = c(4, 5, 6))
print(predict(fit, newdata = newx, interval = "confidence"))

# ANOVA
groups <- factor(rep(1:3, each = 30))
values <- c(rnorm(30, 5), rnorm(30, 6), rnorm(30, 5.5))
print(summary(aov(values ~ groups)))

# Distribution functions
print(pnorm(1.96))              # P(Z <= 1.96)
print(qnorm(0.975))             # 97.5th percentile
print(dbinom(2, size = 5, prob = 0.5))

Explanation

R ships with a wide range of statistical primitives: summary measures, t-tests, correlation tests, ANOVA, and linear models all return objects with helpful print and summary methods. Distribution functions follow a naming convention—d for density, p for cumulative, q for quantile, r for random draws. lm fits linear regressions whose coefficients, confidence intervals, and predictions are all accessible programmatically.

More R Snippets