From hb at maths.lth.se  Wed Apr  5 11:18:21 2006
From: hb at maths.lth.se (Henrik Bengtsson)
Date: Wed, 5 Apr 2006 11:18:21 +0200
Subject: [Rd] Return function from function and Recall()
Message-ID: <59d7961d0604050218u6c570234h56b9d65b7dcbc387@mail.gmail.com>

Hi,

yesterday I got very useful feedback on what is the best way to return
a function from a function.

Now, I run into a problem calling a returned function that down the
stream uses Recall().  Below is a self-contained example.  I took away
yesterday's code for returning a minimal environment for the function,
because that is not related to this problem.

getPredictor <- function(x, y) {
  sp <- smooth.spline(x=x, y=y, keep.data=FALSE)
  function(x, ...) predict(sp$fit, x, ...)$y
}

# Simulate data
x <- 1:10
y <- 1:10 + rnorm(length(x))

# Estimate predictor function
fcn <- getPredictor(x,y)

# No extrapolation => no Recall()
ypred <- fcn(x)
print(ypred)
# Gives:  # [1]  2.325181  2.756166  ...

# With extrapolation => Recall()
xextrap <- c(0,x)
ypred <- fcn(xextrap)
# Gives:  # Error in Recall(object, xrange) : couldn't find
# function "predict.smooth.spline.fit"

To see what's the function looks like, do

pfcn <- getAnywhere("predict.smooth.spline.fit")$obj[[2]]
page(pfcn)

A workaround is to set the predict.smooth.spline.fit() in .GlobalEnv, i.e.

 predict.smooth.spline.fit <- pfcn

Does Recall() have a problem because predict.smooth.spline.fit() is
not exported, or what is going on?  Are there alternatives to the
above workaround?  I can see how such a workaround can become very
complicated with complex functions where it is hard to predict what
functions are called when.

/Henrik

PS, may I suggest to modify page() so that
'page(getAnywhere("predict.smooth.spline.fit"))' works? DS.



[Rd] Return function from function and Recall()
Henrik Bengtsson