Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created June 7, 2024 03:05
Show Gist options
  • Save abikoushi/dffa2d21042dff45f8c9f059f7a7f2ec to your computer and use it in GitHub Desktop.
Save abikoushi/dffa2d21042dff45f8c9f059f7a7f2ec to your computer and use it in GitHub Desktop.
Categorical sampling (for Rcpp)
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
mat rcate(const int N, const rowvec & p){
int K = p.n_cols;
rowvec cump = cumsum(p);
mat x(N, K);
x.fill(0);
for(int n = 0; n<N; n++){
double U = R::runif(0,1);
if(U<=cump(0)){
x(n,0) += 1;
}else{
for(int k=1; k<K; k++){
if(cump[k-1]<U & U<=cump[k]){
x(n,k) += 1;
}
}
}
}
return(x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment