Created
June 7, 2024 03:05
-
-
Save abikoushi/dffa2d21042dff45f8c9f059f7a7f2ec to your computer and use it in GitHub Desktop.
Categorical sampling (for Rcpp)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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