[R] subsetting within a function

Pamela McCaskie pmccask at cyllene.uwa.edu.au
Thu Dec 30 11:22:59 CET 2004

I am trying to write a function around a glm or similar function, in which
I can pass the subsetting constraint as an argument to the function, but I
am having trouble.

the following commands (if I wanted SEX==0 to be my subset) in the global
environment work fine:

subexpr <- expression(SEX==0)
subtest <- with(mydata, eval(subexpr))
test.glm <- glm(y~x1+x2, data=mydata, family=binomial, subset=subtest)

And so my attempt to wrap a simple function around this looks like:
test.fun <- function(formula, mydata, sub=NULL){
  subs <- with(mydata, eval(sub))
  fit.glm <- glm(formula=formula, data=mydata, family=binomial, subset=subs)

But when I tested it out with
test <- test.fun(y~x1+x2, mydata=testdata, sub=expression(SEX==0))

I get:
Error in "[.data.frame"(structure(list(N_ASTHMA = as.integer(c(0, 0, 0,  :
        invalid subscript type
I'm guessing that it's looking in the global environment for
subs, but I'm not sure
how to fix this. Any help would be greatly appreciated.
Pamela A McCaskie
BSc(Mathematical Sciences)(Hons)

Western Australian Institute for Medical Research
University of Western Australia
SCGH Campus
Ground Floor, B Block
QE-II Medical Centre
Hospital Avenue, Nedlands
Western Australia  6009
Email:        pmccask at cyllene.uwa.edu.au
Phone:        +61-8-9346 1612
Mob:          0417 926 607

More information about the R-help mailing list