Daniel Almirall
2004-Dec-29 22:54 UTC
[R] Updating a formula w a portion of another formula
R-list, Suppose I have oldfmla <- y ~ x I would like to update it to y ~ x + z which I know I can get using newfmla <- update(oldfmla, ~ . + z) However, what if I have fmlatmp <- ~ z Can I combine oldfmla and fmlatmp to get y ~ x + z some how? Clearly, newfmla <- update(oldfmla, ~ . + fmlatmp) will not work. Thanks in advance, Danny
Gabor Grothendieck
2004-Dec-30 02:34 UTC
[R] Updating a formula w a portion of another formula
Daniel Almirall <dalmiral <at> umich.edu> writes: : : R-list, : : Suppose I have : : oldfmla <- y ~ x : : I would like to update it to y ~ x + z which I know I can get using : : newfmla <- update(oldfmla, ~ . + z) : : However, what if I have : : fmlatmp <- ~ z : : Can I combine oldfmla and fmlatmp to get y ~ x + z some how? : : Clearly, : : newfmla <- update(oldfmla, ~ . + fmlatmp) : : will not work. : : Thanks in advance, : Danny Assuming we have: old <- y ~ x tmp <- ~ z Then type in this: template <- . ~ . + X template[[3]][[3]] <- tmp[[2]] update(old, template) In the above we used the fact that formulas are represented internally as trees whose parts can be extracted using indexing. After running the above, try entering the following to get a better idea of how formulas are represented: as.list(old) as.list(tmp) as.list(template) as.list(template[[3]])
Gabor Grothendieck
2004-Dec-30 04:20 UTC
[R] Updating a formula w a portion of another formula
Gabor Grothendieck <ggrothendieck <at> myway.com> writes:
:
: Daniel Almirall <dalmiral <at> umich.edu> writes:
:
: :
: : R-list,
: :
: : Suppose I have
: :
: : oldfmla <- y ~ x
: :
: : I would like to update it to y ~ x + z which I know I can get using
: :
: : newfmla <- update(oldfmla, ~ . + z)
: :
: : However, what if I have
: :
: : fmlatmp <- ~ z
: :
: : Can I combine oldfmla and fmlatmp to get y ~ x + z some how?
: :
: : Clearly,
: :
: : newfmla <- update(oldfmla, ~ . + fmlatmp)
: :
: : will not work.
: :
: : Thanks in advance,
: : Danny
:
: Assuming we have:
:
: old <- y ~ x
: tmp <- ~ z
:
: Then type in this:
:
: template <- . ~ . + X
: template[[3]][[3]] <- tmp[[2]]
: update(old, template)
:
One can alternately use substitute avoiding determination of
the precise indices of X. Note that the eval is required
since substitute returns a call object and eval turns it
back into a formula (as per the Note near the bottom of
?substitute):
tmp2 <- eval(substitute(. ~ . + X, list(X = tmp[[2]])))
update(old, tmp2)