Skip to content

Instantly share code, notes, and snippets.

@wrathematics
Created August 11, 2017 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrathematics/07d240b267883c93ef79ebf33a6b734b to your computer and use it in GitHub Desktop.
Save wrathematics/07d240b267883c93ef79ebf33a6b734b to your computer and use it in GitHub Desktop.
// ----- count.c
// build with R CMD SHLIB count.c (or put it in the package, w/e)
#include <R.h>
#include <Rinternals.h>
SEXP colsum_which_eq0(SEXP nrows_, SEXP ncols_, SEXP J_)
{
SEXP ret;
const int nrows = INTEGER(nrows_)[0];
const int ncols = INTEGER(ncols_)[0];
const int *const restrict J = INTEGER(J_);
const int len = LENGTH(J_);
PROTECT(ret = allocVector(INTSXP, ncols));
int *const restrict ret_ptr = INTEGER(ret);
for (int j=0; j<ncols; j++)
ret_ptr[j] = nrows;
for (int k=0; k<len; k++)
{
int nnz = 0;
int col = J[k];
while (col == J[k] && k < len)
{
nnz++;
k++;
}
ret_ptr[col-1] = nrows - nnz;
if (nnz)
k--;
}
UNPROTECT(1);
return ret;
}
### count.r
# assumes the data is in COO/"simple triplet"/AIJ format. This is the easiest to convert
# to CSR/CSC if that's what you're really interested in (don't use CSR)
x = coop:::dense_stored_sparse_mat(100, 10, 0.1)
x[, 5] = 0
storage.mode(x) = "integer"
coo = slam::as.simple_triplet_matrix(x)
dyn.load("count.so")
.Call("colsum_which_eq0", coo$nrow, coo$ncol, coo$j)
colSums(x == 0L) # compare
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment