[R] Advice on parsing formulae
Heather Turner
Heather.Turner at warwick.ac.uk
Thu Dec 16 14:23:17 CET 2004
Okay, well you could define a tvar function as follows
tvar <- function(term) term
Then stick to fm1
X <- model.matrix(fm1,keep.order=TRUE)
pAssign <- attr(X, "assign")
tvar.terms <- terms( fm1, specials = "tvar",keep.order=TRUE )
idx <- attr(tvar.terms,"specials")$tvar
if (attr(tvar.terms,"response")) idx <- idx -1
all.labels <- attr(tvar.terms, "term.labels")
tvar.labels <- all.labels[idx]
tvarAssign <- match(pAssign, match(tvar.labels, all.labels))
tvarAssign[is.na(tvarAssign)] <- 0
I think that the specials attributes is an index of the variables attribute, hence I have replaced
if (attr(tvar.terms,"intercept")) idx <- idx -1
with
if (attr(tvar.terms,"response")) idx <- idx -1
check e.g.
fm1 <- Y ~ tvar(x:A) + tvar(z) + u + tvar(B) + tvar(poly(v,3))
fm1 <- ~ 1 + tvar(x:A) + tvar(z) + u + tvar(B) + tvar(poly(v,3))
Heather
From: "Claus Dethlefsen" <dethlef at math.aau.dk>
To: "'Heather Turner'" <Heather.Turner at warwick.ac.uk>, <r-help at stat.math.ethz.ch>
Date: 12/16/04 8:33am
Subject: RE: [R] Advice on parsing formulae
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?
When my above problem is solved, I can (with the help from Heather Turner
and Chuck Berry) do the following
## define som data
x <- z <- u <- v <- rnorm(5)
A <- B <- factor( rep( c(1,2), c(3,2) ) )
## define my formula fm1 and manually create fm2.
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)
## extract the term.labels from fm2, make the design matrix and extract
'assign'
term.labels <- unname(sapply(attr(terms(fm2), "term.labels"),
removeSpace))
X <- model.matrix(fm2,keep.order=TRUE)
pAssign <- attr(X, "assign")
## Now, extract the tvar-terms from fm1
tvar.terms <- terms( fm1, specials = "tvar",keep.order=TRUE )
idx <- attr(tvar.terms,"specials")$tvar
if (attr(tvar.terms,"intercept")) idx <- idx -1
tvar <- attr(terms(fm2,keep.order=TRUE),"term.labels")[idx]
tvar <- unname( sapply( tvar, removeSpace) )
## Finally, combine the information to get the vector I asked for
tvarAssign <- match(pAssign, sort(match(tvar, term.labels)))
tvarAssign[is.na(tvarAssign)] <- 0
Mrs H Turner
Research Assistant
Dept. of Statistics
University of Warwick
More information about the R-help
mailing list