[R] transform R to C

Charles C. Berry cberry at tajo.ucsd.edu
Mon Jan 5 20:05:06 CET 2009


On Mon, 5 Jan 2009, Andreas  Wittmann wrote:

> Dear R users,
>
> i would like to transform the following function from R-code to C-code 
> and call it from R in order to speed up the computation because in my 
> other functions this function is called many times.
>
>
> `dgcpois` <- function(z, lambda1, lambda2)
> {
>  `f1` <- function(alpha, lambda1, lambda2)
>     return(exp(log(lambda1) * (alpha - 1) - lambda2 * lgamma(alpha)))
>
>  `f2` <- function(lambda1, lambda2)
>    return(integrate(f1, lower=1, upper=Inf, lambda1=lambda1, lambda2=lambda2)$value)
>
>  return(exp(log(lambda1) * z - lambda2 * lgamma(z + 1) -
>             log(f2(lambda1=lambda1, lambda2=lambda2))))
> }
>
>
> In order to do this i read for example dgamma.c or dpois.c but for my it 
> seems rather cryptic and so i would like get some advice in writing the 
> c-function. First of all i think i cannot call the integrate r-function 
> from c so i have to use the internal c-function of integrate here?

You can do what integrate() does:

         wk <- .External("call_dqagi", ff, rho = environment(),
             as.double(bound), as.integer(inf), as.double(abs.tol),
             as.double(rel.tol), limit = limit, PACKAGE = "base")

and save a bit of time by doing the setup in integrate once only and 
call just .External from within your other functions.


Or you can follow the directions in

 	Writing R Extensions

...

 	6.9 Integration

 	The C code underlying integrate can be accessed directly. The user needs
 	to supply ....

and also note in '6.7 Numerical analysis subroutines' that the API gives 
you everything else you need (e.g. lgammafn) for  a C version of dgcpois.

HTH,

Chuck


>
> Thanks,
>
> Andreas
> --
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901




More information about the R-help mailing list