1.4.2 Formulas
A formula is written with ~, as R writes y ~ x1 + x2: the response, then the predictor terms. ~ quotes its body, except for its transforms, so the column names are written as identifiers, or as strings when they are not identifiers or are words of the formula language (all, surv and the operators +, -, *, : and ^):
> (~ bp age dose) (~ bp age dose)
> (formula-predictor-names (~ bp age dose) patients) '("age" "dose")
Since ~ quotes the names itself, a quoted name, such as 'age, is a syntax error that says to write age.
The simplest terms are:
a column name, which selects that column;
all, every column that is not a response, in the table’s order (R’s .);
(- term excluded ...), the columns of term except those of the excluded terms (R’s -).
Several terms after the response are joined as by +, and a column selected twice counts once. formula-predictor-names shows what a formula selects from a table:
> (formula-predictor-names (~ bp all) patients) '("age" "dose" "marker" "relapse" "time" "status")
> (formula-predictor-names (~ bp (- all relapse time status)) patients) '("age" "dose" "marker")
> (formula-predictor-names (~ bp (+ marker age) age) patients) '("marker" "age")
all leaves out the response but not the table’s other responses, so the second formula excludes them. A column name that is not in the table is an error:
> (formula-predictor-names (~ bp age weight) patients) formula-predictor-names: the table has no column with this
name
column: "weight"
formula: (~ bp age weight)
columns of the table: '("age" "dose" "marker" "bp"
"relapse" "time" "status")
The formula language also has R’s operators for interactions, crossing, powers and the intercept, written prefix as here or infix as R writes them, which The formula algebra describes; transforms such as (log age), which Transforms describes; and categorical predictors, columns of strings and (factor x), which Categorical predictors describes.
The response is one column for most families. For the Cox family it is (surv time status), as R’s Surv(time, status), and for the multi-response Gaussian family a list of columns, as R’s cbind(y1, y2). Their columns are left out of all too:
> (formula-predictor-names (~ (surv time status) (- all bp relapse)) patients) '("age" "dose" "marker")
A formula is a value. It prints as the ~ form that makes it, and make-formula builds one from data, for names that are only known when the program runs:
> (define predictors '("age" "marker")) > (apply make-formula "bp" predictors) (~ "bp" "age" "marker")