# [Rd] Polymorphism of predict

Greg Snow Greg.Snow at imail.org
Wed Aug 19 21:52:22 CEST 2009

```Instead of using smooth.spline, use lm with spline terms, e.g.:

> library(splines)
> sp.fit <- lm(y~bs(x,4))

Now both use predict.lm for the predictions and all will be consistent.

Hope this helps,

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111

> -----Original Message-----
> From: r-devel-bounces at r-project.org [mailto:r-devel-bounces at r-
> project.org] On Behalf Of Christian Brechbühler
> Sent: Monday, August 17, 2009 2:54 PM
> To: r-devel at stat.math.ethz.ch
> Subject: [Rd] Polymorphism of predict
>
> I can fit a line to a set of given points, e.g.,
>
> > sm.fit <- smooth.spline(1:4,1:4)
> > lm.fit <- lm(y~x, data=list(x=1:4,y=1:4))
>
> Now I have two objects representing the straight line y(x)=x, of class
> "smooth.spline" and "lm", respectively.
> And as could be expected in object orientation, both have a method
> "predict", which I could use for
> interpolating some new points on the line.  So far so good.  BUT the
> two
> methods require different
> arguments, and return different structures:
>
> > predict(sm.fit, 1.5:4)
> \$x
> [1] 1.5 2.5 3.5
>
> \$y
> [1] 1.5 2.5 3.5
>
> > predict(lm.fit, list(x=1.5:4))
>   1   2   3
> 1.5 2.5 3.5
>
> I probably don't understand the motivation behind this design, but it
> seems
> ugly.  If, hoping for nice
> polymorphism, I call predict(lm.fit, 1.5:4), I get an error: "numeric
> 'envir' arg not of length one".
>
> I expected something like the classic OO example, class Shape:  you can
> call
> area() or paint() on
> any object of the class.
>
> Questions:
> * Why does "predict" act so inconsistently?
> * Is there a nicer interface that hides it?
> * Are there plans to change the current design?
>
> Assuming "no" to the latter two -- what are my options?  Create
> as.smooth.spline(...) that would accept an "lm" object?
> My goal is to write OO style code, that doesn't need to know which kind
> it's
> working with.
> Thanks,
> /Christian
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

```