Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created June 12, 2024 11:53
Show Gist options
  • Save abikoushi/bbcfb47b94d88e113b1c875568493298 to your computer and use it in GitHub Desktop.
Save abikoushi/bbcfb47b94d88e113b1c875568493298 to your computer and use it in GitHub Desktop.
Categorical sampling via Rcpp
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
// [[Rcpp::depends(RcppArmadillo)]]
int rcate0(const int & K){
int x = 0;
double U = R::runif(0,1);
if(U > 1/K){
for(int k=1; k<K; k++){
if((k/K)<U & U<=(k+1)/K){
x = k;
}
}
}
return(x);
}
int rcate(const vec & p){
int K = p.n_elem;
//Rprintf("%d",K);
vec cump = cumsum(p);
int x = 0;
double U = R::runif(0,1);
if(U > cump(0)){
for(int k=1; k<K; k++){
if(cump[k-1]<U & U<=cump[k]){
x = k;
}
}
}
return(x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment