3

I'm trying to draw a random sample from 1,2,3,4 under a given probability vector of length four in C, with the help of Rmath.h. I found this line of code could do this for me.

inline void rmultinom(int n, double* prob, int k, int* rn)

For example, I can write it to draw one random sample.

double p[4]={.1, .2, .3, .2};

rmultinom(1, p, 1, int* rn)

However, I'm lost what this 4th argument should be. In R, the rmultinom function only requires the first three arguments. Another question is what is returned from this function. Is there any convenient way for it to return with one of 1, 2, 3, 4?

Ashley
  • 67
  • 1
  • 7
  • 2
    Looks like rn is the return value. Pass the address of the int variable you want to use to store the result. Also k, looks like the size of the prob vector. – bruceg Aug 12 '20 at 02:01
  • 1
    Yeah, notice the function has a void return type so it doesn't actually "return" anything. It expects you to pass in a pointer to the array you want to fill up with values. It will fill in the data for you there. – MrFlick Aug 12 '20 at 02:05

1 Answers1

2

Here's a simple example

#define MATHLIB_STANDALONE 1
#include "Rmath.h"
#include <stdio.h>

int main(int argc, char** argv) {
    int draws = 100;
    int classes = 4;
    int vals[classes];
    double probs[4] = {0.1, 0.2, 0.4, 0.3};

    set_seed(123, 456);
    rmultinom(draws, probs, classes, vals);

    for(int j=0; j < classes; j++) {
        printf("Count of class %i drawn: %i\n", j, vals[j]);
    }
    return 0;
}

Here we make 100 draws from a multinational distribution with 4 classes. We get back a vector of length 4 that says how many values were in each of those classes. For example I got

Count of class 0 drawn: 9
Count of class 1 drawn: 14
Count of class 2 drawn: 43
Count of class 3 drawn: 34
MrFlick
  • 195,160
  • 17
  • 277
  • 295