Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update formula in R

Tags:

r

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!

like image 291
FairyOnIce Avatar asked Aug 06 '13 00:08

FairyOnIce


1 Answers

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".

like image 119
agstudy Avatar answered Nov 15 '22 22:11

agstudy