# [R] polynomial

Pfaff, Bernhard Bernhard.Pfaff at drkw.com
Thu Oct 10 09:51:32 CEST 2002

```Hello Ben,

would the supplementary package 'polynom' of help to you?

library(polynom)
p <- polynomial(c(1,-1.11,0,0,0.18))

Rgds,
Bernhard

-----Original Message-----
From: Thomas Lumley [mailto:tlumley at u.washington.edu]
Sent: 10 October 2002 00:43
To: bolker at zoo.ufl.edu
Cc: R help list
Subject: Re: [R] polynomial

On Wed, 9 Oct 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])
)
> }
>

Well if x is a scalar as in your example
n<-length(coef)-1
sum(coef*x^(0:n))
seems simpler, or if x is a vector then
n<-length(coef)-1
rowSums(coef*outer(0:n,x,"^"))
or if it's a long enough vector that you don't want n copies of it
rval<-coef[1]
xn<-x
n<-length(coef)
for(i in 2:n){
rval<-rval+coef[i]*xn
xn<-xn*x
}

Unlike lapply, which is actually faster than a for() loop, apply() is
basically a clarity optimisation rather than a speed optimisation, and in
this case I don't think it's clearer.

-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
_._

----------------------------------------------------------------------
If you have received this e-mail in error or wish to read our e-mail
disclaimer statement and monitoring policy, please refer to
http://www.drkw.com/disc/email/ or contact the sender.
----------------------------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```