Reputation: 9809
How can I remove NULL elements of a simple list using Rcpp
?
Or how can I translate this R-function to Rcpp
?
x[!sapply(x, is.null)]
Some R data to test:
x <- list("a"=1, "b"=NULL, "c"=NULL, "d"=2)
x <- list("b"=NULL, "c"=NULL)
This is what I tried so far: The first one breaks R & RStudio and the second one returns a list of integers.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
// Remove the NULL elements iteratively in a for loop (breaks RStudio)
List rm_null(List L) {
List Lcl = clone(L);
for (int i = 0; i < Lcl.length(); ++i){
if (Lcl[i] == R_NilValue) {
Lcl = Lcl[-i];
}
}
return(Lcl);
}
// [[Rcpp::export]]
// Create a numeric vector with the indices to keep and subset the list afterwards
List rm_null1(List L) {
List Lcl = clone(L);
NumericVector ind(Lcl.length());
for (int i = 0; i < Lcl.length(); ++i){
if (Lcl[i] != R_NilValue) {
ind[i] = i;
}
}
return(Lcl[ind]);
}
Upvotes: 0
Views: 212
Reputation: 11728
You can do
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List rm_null(List x) {
int n = x.size();
LogicalVector to_keep(n);
for (int i = 0; i < n; i++) {
to_keep[i] = !Rf_isNull(x[i]);
}
return x[to_keep];
}
Upvotes: 3