[R] polynomial

Achim Zeileis zeileis at ci.tuwien.ac.at
Wed Oct 9 22:28:49 CEST 2002


Ben Bolker wrote:
> 
>   Any better (more efficient, built-in) ideas for computing
> 
>  coef[1]+coef[2]*x+coef[3]*x^2+ ...
> 
>  than
> 
> polynom <- function(coef,x) {
>   n <- length(coef)
> 
> sum(coef*apply(matrix(c(rep(x,n),seq(0,n-1)),ncol=2),1,function(z)z[1]^z[2]))
> }
> 
> ?

I think the function 
  polynom2 <- function(x, coef) sum(coef * x^seq(0,length(coef)-1))
is a little bit simpler and quicker for high order polynoms. But if you
want to be able to compute the function for vector-valued x, then you
might need something like
  polynom3 <- function(x, coef)
    apply(coef * sapply(as.matrix(x),
    function(x) x^seq(0,length(coef)-1)), 2, sum)

Then you can do:
R> mycoef <- rnorm(10000) 
R> polynom(mycoef, 0.5)
[1] -0.1422343
R> polynom2(0.5, mycoef)
[1] -0.1422343
R> polynom2(0.75, mycoef)
[1] -1.395595
R> polynom3(c(0.5, 0.75), mycoef)
[1] -0.1422343 -1.3955947

Best,
Z


>   Ben
> --
> 318 Carr Hall                                bolker at zoo.ufl.edu
> Zoology Department, University of Florida    http://www.zoo.ufl.edu/bolker
> Box 118525                                   (ph)  352-392-5697
> Gainesville, FL 32611-8525                   (fax) 352-392-3704
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list