[R] Advice on parsing formulae

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Dec 16 10:22:27 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? 

Eek, no!!

> Is there an
> easy way of doing this?

Not really. Recursively descend the parse tree and replace calls to
tvar with its argument. Probably ends with one of those 10-line
functions that take hours to get right... Something like this would go
in the middle

if (is.call(e))
  if (e[[1]]==as.name("tvar")) 
    e[[2]]
  else
    for (i in 2:length(e)) 
       e[[i]] <- myfun(e[[i]])
else
  e

If you don't mind getting left with a couple of extra parentheses,
this seems to work:

> eval(substitute(substitute(fm1,list(tvar=as.name("("))),list(fm1=fm1)))
Y ~ 1 + (x:A) + (z) + u + (B) + (poly(v, 3))

(Note to self: we need a substitute() variant that takes a variable,
not a literal as the first argument.)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list