[R] polynomial

Thomas Lumley tlumley at u.washington.edu
Thu Oct 10 00:42:55 CEST 2002


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



More information about the R-help mailing list