[R] probelem of function inside function

About this list Date view Thread view Subject view Author view Attachment view

From: array chip (arrayprofile@yahoo.com)
Date: Thu 26 Jun 2003 - 06:48:23 EST


Message-id: <20030625204823.35956.qmail@web41202.mail.yahoo.com>

Hi,

I encountered a problem when I am trying to write my
own function which contains another function. To
simplify a problem, I tried the following simplified
function, hope someone can idenfity the problem for
me.

I have a simple data frame called "testdata" as
following:

>
testdata<-data.frame(cbind(x=c(129,109,52,118,217,278,606,198,99,133),y=c(89,118,99,137,34,14,130,30,131,30)))
> testdata
     x y
 1 129 89
 2 109 118
 3 52 99
 4 118 137
 5 217 34
 6 278 14
 7 606 130
 8 198 30
 9 99 131
10 133 30

I have write a simple function (nonsense):

> f.fun<-function(var,fdata) {
      fdata<-data.frame(fdata)
      fit<-lm(y~1,data=fdata)

      f.addterm<-function(x,fit,f.data) {
        fdata<-f.data
           fff<-paste('~.',x,sep='+')
           try(addterm(fit,as.formula(fff))$AIC[2])
      }

      f.addterm(var,fit,fdata)
 }

This function simply add the "x" variale to the linear
regression with intercept only using addterm, and
return the AIC of the new model. I know I can simply
do this with stepAIC of MASS, but for my own
situation, I want to try something more complicated.

so when I execute the following command, I got an
error message:

> f.fun(var='x',fdata=testdata)
Problem in eval(oc, list()): Object "fdata" not found
Use traceback() to see the call stack
[1] "Problem in eval(oc, list()): Object \"fdata\" not
found \nUse traceback() to see the call stack"
attr(, "class"):
[1] "Error"

I guess the reason is that within the inside function
"f.addterm", the dataset "fdata" can't be seen, but I
don't know why because I think I have passed the
dataset into the inside function.

However, if I create a dataset called "fdata" outside
the function "f.fun" at the very beginning, everything
will be fine. This is obvious because now "fdata" is a
global dataset now.

> fdata=testdata
> f.fun(var='x',fdata=testdata)
[1] 80.81915

Thanks

Zander.

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Tue 01 Jul 2003 - 09:12:09 EST