Skip to content
Monte

R

Run these in RStudio or the R console. x and y are numeric vectors; df is a data frame.

Mean, median
mean(x)
median(x)
Base R has no mode function; names(which.max(table(x))) gives the most frequent value.
Sample SD and variance
sd(x)
var(x)
Both divide by n − 1.
Correlation and covariance
cor(x, y)
cov(x, y)
Combinations
choose(5, 2)
Returns 10.
Binomial
dbinom(2, size = 8, prob = 0.2)
pbinom(2, size = 8, prob = 0.2)
d is exactly 2, p is at most 2.
Poisson
dpois(3, lambda = 3)
ppois(4, lambda = 6)
Normal areas and cutoffs
pnorm(525, mean = 400, sd = 50)
qnorm(0.9, mean = 400, sd = 50)
Critical values
qnorm(0.975)
qt(0.975, df = 15)
CI for a mean from data
t.test(x, conf.level = 0.95)$conf.int
CI for a proportion, textbook formula
p <- 120 / 200
p + c(-1, 1) * qnorm(0.95) * sqrt(p * (1 - p) / 200)
prop.test uses a different method, so its numbers won't match the formula.
Regression
fit <- lm(sales ~ adv, data = df)
summary(fit)
Coefficients, R², t tests, and the F test in one table.
Prediction interval
predict(fit, data.frame(adv = 8), interval = "prediction")
Use interval = "confidence" for the mean response.
VIF
car::vif(fit)
Needs the car package: install.packages("car").