celestialgod

Rcpp CV index

Nov 2nd, 2015
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.69 KB | None | 0 0
  1. library(Rcpp)
  2. library(RcppArmadillo)
  3.  
  4. sourceCpp(code = '
  5. // [[Rcpp::depends(RcppArmadillo)]]
  6. #include <RcppArmadillo.h>
  7. using namespace Rcpp;
  8. using namespace arma;
  9.  
  10. // [[Rcpp::export]]
  11. uvec cvfold_index_f(const uword n, const uword fold)
  12. {
  13.  uword fold_n = n / fold, rem = n - fold_n * fold;
  14.  uvec tmp_vec = linspace<uvec>(0, fold - 1, fold),
  15.    index = vectorise(repmat(tmp_vec, fold_n, 1));
  16.  if (rem > 0)
  17.    index = join_cols(index, index.head(rem));
  18.  
  19.  // random permutation
  20.  int j;
  21.  for (int i = 0; i < n; i++)
  22.  {
  23.    j = as_scalar(randi<uvec>(1, distr_param(i, n - 1)));
  24.    index.swap_rows(i, j);
  25.  }
  26.  return index;
  27. }')
  28. cvfold_index_f(11, 3) # 2 2 1 2 0 1 0 0 0 1 1
Advertisement
Add Comment
Please, Sign In to add comment