Created
August 11, 2017 14:01
-
-
Save wrathematics/07d240b267883c93ef79ebf33a6b734b to your computer and use it in GitHub Desktop.
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
// ----- 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