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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With