[R] vectorizing a function

Robin Hankin r.hankin at auckland.ac.nz
Wed Oct 23 03:32:00 CEST 2002


Dear R-xperts

I have just written a little hypergeometric function, included below
[the hypergeometric function crops up when solving a common type of
ODE].

It works fine on single values of the primary argument z, but
vectorizing it is getting confusing.

The best I have come up with so far just tests for z being longer than
1 and if so, uses sapply() recursively.  This is fine, except that it
doesn't preserve the dimensions correctly if z is a matrix or an
array.  And the function doesn't work properly if z is a scalar but A
is a vector.

besselI() does The Right Thing (tm), but it is internal ; what is the
best way to vectorize this type of function?





hypergeo <- function(A,B,C,z,tol=1e-6){
  if(length(z) > 1) {
    return(sapply(z,hypergeo,A=A,B=B,C=C,tol=tol))
  } else { 
    term <- tmp <- 1
    
    for(n in 1:100){
      term <- term*A*B/C
      term=term*z/n
      
      partial.sum <- tmp + term
      if ((abs(partial.sum-tmp)<tol) || is.infinite(partial.sum)){return(partial.sum)}
      A <- A+1
      B <- B+1
      C <- C+1
      tmp <- partial.sum
    }
    return (NaN)
  }
}


-- 

Robin Hankin, Lecturer,
School of Geography and Environmental Science
Tamaki Campus
Private Bag 92019 Auckland
New Zealand

r.hankin at auckland.ac.nz
tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042

as of: Wed Oct 23 14:25:00 NZDT 2002
This (linux) system up continuously for:  419 days, 20 hours, 07 minutes
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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