Skip to content
Incomplete sheet

This sheet is incomplete and could use some attention. Please submit code snippet suggestions as an issue or PR here.

formula

Create

Action Code Details
Intercept only
y ~ 1
With intercept and single variable
y ~ x
Without intercept, and single variable
y ~ -1 + x
With all variables
y ~ .
No response variable
~ 1
From string
as.formula(str)
From string
eval(parse(text='y ~ x'))
Not recommended

Test

Action Code Details
Is formula
is(f, 'formula')
Is formula or subclass
inherits(f, 'formula')
Formulas are equal
f1 == f2
Formulas are equal
isTRUE(all.equal(f1, f2))
Has response
attr(terms(f), 'response') != 0
Has intercept
attr(terms(f), 'intercept') != 0
Surely there is an easier way

Extract

Action Code Details
Variable names
all.vars(f)
Left-hand side variable names
all.vars(update(f,  ~ 1))
Right-hand side variable names
all.vars(update(f,  1 ~ .))
Environment
environment(f)

Derive

Action Code Details
Add a term
update(f, ~ . + w)
Add terms
update(f, ~ . + w + z)
Set response
update(f, y ~ .)
Set terms
update(f, ~ w + z)
Remove response
update(f, NULL ~ .)
Remove response
formula(delete.response(terms(f)))
Remove intercept
update(f, ~ . + -1)
Remove environment
environment(f) = NULL
Useful for formula serialization to prevent the entire workspace from being serialized along with it

Evaluate

Action Code Details
Evaluate a formula with known coefficients
mm = model.matrix( ~ a + poly(b, 2, raw=TRUE), data.frame(a=1, b=2:4))
pred = coef %*% t(mm)

Convert

Action Code Details
String
deparse(f)
String array
as.character(f)