[R] call step inside a function

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Mon Oct 4 23:05:27 CEST 2004



weihong wrote:
> I am wondering why my function works fine in R1.7.1 and R1.8.1 but not in 
> R1.9.0. I thought it's an environment related problem but I can't solve it.
> 
> 
>>data
> 
>    weta jd
> 1     1  4
> 2     2 13
> 3     2 13
> 4     6  4
> 5     1  3
> 6     1  7
> 7     2 10
> 8     3 10
> 9     1  8
> 10    1  8
> 11    3  6
> 12    1  9
> 13    1  5
> 14    1  1
> 15    3 13
> 16    1  2
> 17    2  2
> 18    7 11
> 19    1  3
> 20    5  4
> 21    1  6
> 22    4  9
> 23    1  6
> 24    4  5
> 25    5  5
> 26    2  6
> 
> 
>>program
> 
> function(dataset)
> {
>         tmp<-glm(weta~1, family=poisson, data=dataset)
>         tmp.f<-step(tmp,~.+jd)    
> }
> 
> When I run program(data) in 1.9.0, an error message appears:
> 
> Error in model.frame.default(formula = WETA ~ jd, data = dataset, 
> drop.unused.levels = TRUE) :
>         Object "dataset" not found
> 
> 
> Thanks for help in advance!
> 
> Weihong Zeng
> University of Albert
> 

This is a scoping problem. There may be better answers but the following 
trick has worked for me in the past:

f <- function(z) {
   eval(substitute(fit <- glm(weta ~ 1, family = poisson, data = z),
                   list(z = z)))
   step(fit, ~ . + jd)
}

--sundar




More information about the R-help mailing list