Hi all -
I had a need to create a version of R’s %in%
function for Stan, so I decided to post the code here in case anyone finds it useful. Essentially checks if an integer matches a list of integers, and is useful for determining if an element index is in a pre-specified list of indices. It is only vectorized one way (the list of possible index matches), instead of 2-way as R’s is.
test_R_in.stan (790 Bytes)
R_in.R (326 Bytes)
Here’s the Stan code, and demonstration R code is in the attached files:
functions {
// function that is comparable to R's %in% function
// pos is the value to test for matches
// array pos_var is the 1-dimensional array of possible matches
// returns pos_match=1 if pos matches at least one element of pos_var and pos_match=0 otherwise
// example code:
// if(r_in(3,{1,2,3,4})) will evaluate as TRUE
int r_in(int pos,int[] pos_var) {
int pos_match;
int all_matches[size(pos_var)];
for (p in 1:(size(pos_var))) {
all_matches[p] = (pos_var[p]==pos);
}
if(sum(all_matches)>0) {
pos_match = 1;
return pos_match;
} else {
pos_match = 0;
return pos_match;
}
}
}