Search code examples
crcran

Where is the code for recycling `rbinom` inputs?


From the documentation, rbinom takes three arguments, n, size, and prob. The answer to this question states that if prob is a vector, it is recycled until n is reached. I want to find that code!

The R source immediately calls a C function:

> rbinom
function (n, size, prob) 
.Call(C_rbinom, n, size, prob)
<bytecode: 0x113526220>
<environment: namespace:stats>

Searching the Github mirror for R gets me the this rbinom C function, but it only takes two arguments. Where is n? Where is the recycling of prob to the length of n? I can't find it in this function definition.

double rbinom(double nin, double pp)
{
...
}

Searching for all C files containing rbinom, the only other relevant-seeming C file I found is this one, but I don't understand it. Is this where the recycling happens, or is there another function definition somewhere that I am missing?


Solution

  • With the helpful guidance of stack overflow I managed to answer this to my satisfaction. I'm not sure about the details, but here goes:

    > rbinom

    calls this line

    rbinom <- function(n, size, prob) .Call(C_rbinom, n, size, prob)

    located at line 149 of /src/library/stats/R/distn.R

    This in turn is going to call

    static R_INLINE SEXP random2(SEXP sn, SEXP sa, SEXP sb, ran2 fn, SEXPTYPE type)

    with sn=n, sa=size, sb=prob and fn=rbinom.

    In that function the code you want is on ine 185: rx = fn(ra[i % na], rb[i % nb]); which shows that rbinom is called recycling both the size and prob parameter.

    The connection between random2 and rbinom is established with a preprocessor in the same file as the function random2.

    DEFRAND2_INT(rbinom)
    
    #define DEFRAND2_INT(name) \
        SEXP do_##name(SEXP sn, SEXP sa, SEXP sb) { \
            return random2(sn, sa, sb, name, INTSXP); \
        }