[R] Advice on parsing formulae

Gabor Grothendieck ggrothendieck at myway.com
Thu Dec 16 15:42:15 CET 2004


Claus Dethlefsen <dethlef <at> math.aau.dk> writes:

: 
: Thank you for the advice. I have now boiled my problem down to the
: following:
: 
: How do I create fm2 from fm1 ?
: 
: fm1 <-  Y ~ 1 + tvar(x:A) + tvar(z) + u + tvar(B) + tvar(poly(v,3))
: fm2 <-  Y ~ 1 + x:A + z + u + B + poly(v, 3)
: 
: Thus, how do I simply remove tvar( * ) from a formula? Do I have to write a
: function to parse the string and then re-create the formula? Is there an
: easy way of doing this?


If its ok to leave in some extra parentheses you could 
1. convert it to a character string, fm1.str and then
2. use gsub to replace all occurrences of "tvar" with "" and 
   then convert it back to a formula:

fm1.str <- paste( as.character(fm1)[c(2,1,3)], collapse = "" )
fm2 <- as.formula( gsub("tvar", "", fm1.str) )




More information about the R-help mailing list