[R] glm inside one self-defined function
Bill.Venables at csiro.au
Bill.Venables at csiro.au
Wed Aug 23 05:54:28 CEST 2006
Mike Wolfgang asks:
>
> From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Mike Wolfgang
> Sent: Wednesday, 23 August 2006 1:31 PM
> To: R-help list
> Subject: [R] glm inside one self-defined function
>
> Hi list,
>
> I've searched in R-help and found some related discussions but still
could
> not understand this type of error. My own function is pretty complex,
so I
> would not put it here, but the basic algorithm is like this:
> myfun<-function(k){
> mydata<-...#by someway I create a data frame
> mymodel<-glm(y~.,family=binomial(),data=mydata)
> ...#some other stuff
> }
I think you are leaving out something. Here is a test of what you
claim gives a problem (R 2.3.1, Windows):
> myfun <- function(n) {
+ z <- rnorm(n)
+ mydata <- data.frame(x = z,
+ y = rbinom(n, size = 1, prob = exp(z)/(1+exp(z))))
+ fm <- glm(y ~ x, binomial, mydata)
+ fm
+ }
>
> myfun(100)
Call: glm(formula = y ~ x, family = binomial, data = mydata)
Coefficients:
(Intercept) x
0.1587 1.0223
Degrees of Freedom: 99 Total (i.e. Null); 98 Residual
Null Deviance: 137.6
Residual Deviance: 118.3 AIC: 122.3
Not even a murmur of complaint. (This also works in S-PLUS 7.0 but
earlier versions of S-PLUS gave a problem rather like the one you note,
curiously.)
Look again at your code and see if the abstract version you give
really matches what you did, may I suggest?
>
> as I execute this function, it gives error like this
> Error in inherits(x, "data.frame") : object "mydata" not found
>
> So I guess glm here tries to find "mydata" in the parent environment.
Why
> doesn't it take "mydata" inside the function? How to let glm correctly
> locate it? Is this (scope/environment) mentioned in R manual? Thanks,
>
> Mike
More information about the R-help
mailing list