[R] Advice on parsing formulae

Thomas Lumley tlumley at u.washington.edu
Thu Dec 16 22:47:16 CET 2004


On Thu, 16 Dec 2004, Claus Dethlefsen wrote:

> 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?

One way is to process the formula recursively:

no.tvar<-function(formula){
 	process<-function(expr){
            if (length(expr)==1)
              return(expr)
 	   if(length(expr)==2)
              if ( expr[[1]]==as.name("tvar"))
               return(expr[[2]])
              else return(expr)
            expr[[2]]<-process(expr[[2]])
            expr[[3]]<-process(expr[[3]])
            return(expr)
          }
   formula[[3]]<-process(formula[[3]])
   formula 
}

> no.tvar(fm1)
Y ~ 1 + x:A + z + u + B + poly(v, 3)

This is not the more common sort of problem where you actually want to 
remove terms from a formula (eg Error() in aov, cluster() and strata() in 
coxph).  You want to modify them in place.


 	-thomas




More information about the R-help mailing list