-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix keep_in_bounds so we dont use internal API
- Loading branch information
1 parent
ebdcf1d
commit 1cba917
Showing
1 changed file
with
21 additions
and
38 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,48 +1,31 @@ | ||
#define R_NO_REMAP | ||
#include <R.h> | ||
#include <Rinternals.h> | ||
|
||
SEXP c_keep_in_bounds(SEXP in, SEXP lower, SEXP upper) { | ||
const int * x = INTEGER(in); | ||
const int ll = INTEGER(lower)[0]; | ||
const int lu = INTEGER(upper)[0]; | ||
const R_xlen_t n = Rf_xlength(in); | ||
R_xlen_t i; | ||
SEXP c_keep_in_bounds(SEXP s_in, SEXP s_lower, SEXP s_upper) { | ||
const int *x = INTEGER(s_in); | ||
const int ll = asInteger(s_lower); | ||
const int lu = asInteger(s_upper); | ||
const R_xlen_t n = LENGTH(s_in); | ||
R_xlen_t i, j; | ||
|
||
// fast-forward to first element not in bounds | ||
for (i = 0; i < n; i++) { | ||
if (x[i] == NA_INTEGER || x[i] < ll || x[i] > lu) { | ||
break; | ||
} | ||
} | ||
|
||
// everything ok, in == out | ||
if (i == n) { | ||
return(in); | ||
} | ||
// count the number of elements within bounds | ||
int count = 0; | ||
for (i = 0; i < n; i++) | ||
if (x[i] != NA_INTEGER && x[i] >= ll && x[i] <= lu) count++; | ||
|
||
// allocate output vector | ||
SEXP out = PROTECT(Rf_allocVector(INTSXP, n)); | ||
int * y = INTEGER(out); | ||
R_xlen_t j; | ||
// if all ok, immediatly return without alloc and copy | ||
if (count == n) return(s_in); | ||
|
||
// copy everything up to the first element out of bounds | ||
for (j = 0; j < i; j++) { | ||
y[j] = x[j]; | ||
} | ||
// create a new vector to store the filtered elements | ||
SEXP s_out = PROTECT(allocVector(REALSXP, count)); | ||
double *out = REAL(s_out); | ||
|
||
// process remaining elements | ||
for (i = i + 1; i < n; i++) { | ||
if (x[i] != NA_INTEGER && x[i] >= ll && x[i] <= lu) { | ||
y[j] = x[i]; | ||
j++; | ||
} | ||
// Copy the elements within bounds to the new vector | ||
j = 0; | ||
for (i = 0; i < n; i++) { | ||
if (x[i] != NA_INTEGER && x[i] >= ll && x[i] <= lu) | ||
out[j++] = x[i]; | ||
} | ||
|
||
// resize the vector to the right length | ||
SETLENGTH(out, j); | ||
|
||
// unprotect + return | ||
UNPROTECT(1); | ||
return out; | ||
return s_out; | ||
} |