[Rd] Return function from function and Recall()

Henrik Bengtsson hb at maths.lth.se
Wed Apr 5 11:18:21 CEST 2006


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.



More information about the R-devel mailing list