Formula (~) (R)
A formula in R uses the tilde ~ to describe a relationship between variables, typically 'response ~ predictors'. Formulas are the standard interface for statistical models and many plotting functions.
R
A formula like y ~ x + z is a special R object (not evaluated immediately) that expresses 'model y as a function of x and z'. The left side is the response/dependent variable and the right side the predictors. lm(), glm(), aov(), and many other modeling functions take a formula plus a data frame.
Formula syntax has its own operators: + adds predictors, : denotes an interaction, * means main effects plus interaction, - removes a term, and . means 'all other columns'. y ~ . models y against every other variable in the data. Functions can also appear, e.g. log(y) ~ x.
Formulas also drive plotting (plot(y ~ x, data = df)) and aggregation (aggregate(y ~ group, data, mean)). Because a formula is unevaluated, it captures the variable names so the function can look them up in the supplied data — a key piece of R's statistical design.
Syntax
response ~ predictor1 + predictor2
y ~ . # y against all other columnsExamples
R — mpg ~ wt + hp models mpg as a function of weight and horsepower.
# Fit a linear model using a formula
model <- lm(mpg ~ wt + hp, data = mtcars)
# Extract the fitted coefficients
coef(model)