[R] probelem of function inside function

array chip arrayprofile at yahoo.com
Wed Jun 25 22:48:23 CEST 2003


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.




More information about the R-help mailing list