R-beta: Help accessing variable from a formula
Thomas Lumley
thomas at biostat.washington.edu
Mon Nov 3 18:21:16 CET 1997
On Sat, 1 Nov 1997, Murray Keir wrote:
>
> I have a program which is being feed a formula. One of the terms in
> the formula is going to be r(variablename). r just returns the
> original variable.
>
> r <- function(x) x
>
> The formula is something like
>
> rglm(y ~ x + r(Subject))
>
> What I want to do is get access to the variable Subject directly. Can
> anyone give me any suggestions for doing this?
The terms() command contains some magic for doing this
If you type
R> Terms<-terms(y ~ x + r(Subject),specials="r")
the resulting terms object has an attribute "specials"
R> attr(Terms,"specials")$r
[1] 3
which says that the third column of the model frame will contain the r()
term. Multiple terms are possible
R> Terms<-terms(y ~ x + r(Subject)+r(Object),specials="r")
R> attr(Terms,"specials")$r
[1] 3 4
You may then want to remove the r() from the formula before calling
model.matrix(). This is a bit harder, but there is code in the survival4
package to do it. The function untangle.specials() gives the position of
the r() in the right-hand side of the formula object, and the survival4
package contains a "[.terms" method that allows terms to be removed
R> untangle.specials(Terms,"r")
$vars
[1] "r(Subject)" "r(Object)"
$terms
[1] 2 3
R> Terms<-Terms[-c(2,3)]
R> Terms
y ~ x
attr(,"variables")
list(y, x)
attr(,"factors")
x
y 0
x 1
and so on...
If you want to include the code for untangle.specials() in your own
package you should probably ask Terry Therneau for permission -- the
survival4 code is not GPL -- but I imagine he would be happy for it to be
used with acknowledgement. I wrote the "[.terms" method, so there's no
problem there.
Thomas Lumley
------------------------------------------------------+------
Biostatistics : "Never attribute to malice what :
Uni of Washington : can be adequately explained by :
Box 357232 : incompetence" - Hanlon's Razor :
Seattle WA 98195-7232 : :
------------------------------------------------------------
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
More information about the R-help
mailing list