简体   繁体   中英

How to remove NULL elements of Lists in Rcpp

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]);
}

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM