[R] Function built with segments

Martin Maechler maechler at stat.math.ethz.ch
Sat Dec 15 11:32:22 CET 2007


>>>>> "t" == thierrydb  <thierrydb at gmail.com>
>>>>>     on Fri, 14 Dec 2007 07:19:56 -0800 (PST) writes:

    t> Hello,


    t> I'm new to R. If I have a set of 10 points (X(i), Y(i)), is there an elegant
    t> way to build a function y=f(x) that would be build out of the consecutive
    t> segments of X(j),Y(j) points (with X(j) sorted)?

Yes.
approxfun() !

E.g.

 set.seed(1); x <- runif(10); y <- 3*x + rnorm(10)/10;  plot(x,y)
 myF <- approxfun(x,y)

 myF(0.1)
 ## [1] 0.3734227

and then

  plot(myF, add=TRUE, col=2) ## using plot() method for functions

or simpler to understand:

  xx <- seq(0,1, length=100)
  lines(xx, myF(xx), col=2)


    t> Thank you very much

    t> TDB

you're welcome.
Martin Maechler, ETH Zurich



More information about the R-help mailing list