Skip to content
Prev 24533 / 398502 Next

vectorizing a function

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)
  }
}