Skip to content

probelem of function inside function

4 messages · array chip, Thomas Lumley, Brian Ripley

#
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)))
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):
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:
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.
[1] 80.81915


Thanks

Zander.
#
On Wed, 25 Jun 2003, array chip wrote:

            
<snip>
This looks very much like an S-PLUS error message, and in addition to any
etiquette issues about asking S-PLUS questions on r-help, this is the sort
of question where the answer may actually be quite different in the two
systems.

	-thomas
#
Actually, It is the question I encountered in S-Plus.
Sorry that I forgot to mention. As Simon just pointed
out, the function works fine in R (Thanks!). But in
any case, does anyone know how to solve the problem in
S-Plus?

Thanks
--- Thomas Lumley <tlumley at u.washington.edu> wrote:
#
On Wed, 25 Jun 2003, array chip wrote:

            
Assign to frame 1: see `S Programming'.

addterm (which is not being credited to MASS nor to its author) is
different in R and in S-PLUS.