Re: [S] Using predict() in higher frames.

Bill Venables (
Tue, 19 May 1998 09:21:08 +0930

Alex Zirakzadeh writes:
> Dear Splus users:
> I was hoping one of you can help me determine a way to use the
> predict function in a higher frame. For example, in the same
> frame, I can use the predict function to get the predicted
> value of an loess object.
> > loess.test_loess(y~x,data=mydata)
> > predict(loess.test,newdata=data.frame(x=98))
> [1] 31.074
> However, if I want to pass the loess object as an argument to
> another function and recall the predict from within the
> function, I get an error. In the following example, get.value
> is a function that reads in the loess object and the newvalue,
> and it is supposed to return the predicted value. However, as
> you can see, it does not work.
> > get.value
> function(object, ts, newvalue)
> {
> predict(object, newdata = data.frame(ts = newvalue))
> }
> > get.value(loess.test,x,98)
> Error in loess.matrix(newdata, object$terms): Length of variable 1 is 403 !=
> length of row names (1)
> Dumped

You should look at the traceback() as soon as you see the word
"Dumped". It may be enlightening.

Your basic problem is that you are using the argument `ts' as if
it were sent as a character string. If that's what you want, you
need to do something different. Here is one way to make it work:

> get.value <- function(object, ts, newvalue)
predict(object, newdata = structure(data.frame(newvalue),
names = deparse(substitute(ts))))

> I can always recreate the loess object again from within the function.
> However, I rather not do this duplication.

No, this should not be necessary.

> Any suggestions for doing this? (maybe using one of the
> attributes of the loess object??)
> The reason for creating such a function is to use finite
> difference methods to calculate the slope and the curvature of
> the loess object.

Doing things one at a time like this is going to be very
inefficient and probably require you to write loops later to do
the full calculation. You would be better off drafting the
entire calculation in a vectorizable form and trying to handle it
that way, with only one call to predict and no explicit loops.

As a starter to start you thinking in a non-Fortrany way, try to
draft the calculation without using any for(), while() or
repeat() statements.

Bill Venables.

Bill Venables, Head, Dept of Statistics,    Tel.: +61 8 8303 5418
University of Adelaide,                     Fax.: +61 8 8303 3696
South AUSTRALIA.     5005.   Email:

----------------------------------------------------------------------- This message was distributed by To unsubscribe send e-mail to with the BODY of the message: unsubscribe s-news