I have a formula object form1
form1 = y ~ 1 + x*y
I want to add one more term, say +z in this formula so that my form2 becomes
form2 = y ~ 1 + x*y + z.
I found a very cumbersome way to do this:
terms.form1 <- terms(form1)
terms.labels <- attr(terms.form1,"term.labels")
old.terms <- paste(terms.labels,collapse=" + ")
updated.terms <- paste(old.terms," + z",collapse=" + ")
form2 = as.formula(paste(as.character(form1[[2]]),"~",updated.terms,collapse=""))
Although this gives me the form2, I am wondering if there is a simpler way to do this.
Thank you in advance!
You should use update.formula
:
update(y ~ 1 + x*y, ~ . + z)
y ~ x + y + z + y:x
The .
means "what was previously in this part of the formula".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With