[R] rgamma function

peter dalgaard pdalgd at gmail.com
Sun Jul 15 14:07:37 CEST 2012

On Jul 14, 2012, at 04:55 , Chandler Zuo wrote:

> Hi,
> Has anyone encountered the problem of rgamma function in C? The following simplified program always dies for me, and I wonder if anyone can tell me the reason.
> #include <Rmath.h>
> #include <time.h>
> #include <Rinternals.h>
> SEXP generateGamma ()
> {
>    srand(time(NULL));
>    return (rgamma(5000,1));
> }
> Has anyone encountered a similar problem before? Is there another way of generating Gamma random variable in C?
> P.S. I have no problem compiling and loading this function in R.

It doesn't even give off a warning??

The prototype in Rmath.h is

double  rgamma(double, double);

and you should be returning an SEXP. As soon as something tries to interpret the double value as a pointer -- Poof!

Notice that rgamma in C is not the same function as the R counterpart, in particular it isn't vectorized, so only generates one random number at a time. The long and the short of it is that you need to read up on sections 5.9 and 5.10 of Writing R Extensions.

> Thanks for suggestions in advance!
> --Chandler
> ______________________________________________
> 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.

Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com

More information about the R-help mailing list