如何在 Rcpp 中删除列表的 NULL 元素

How to remove NULL elements of Lists in Rcpp

如何使用 Rcpp 删除简单列表的 NULL 元素?
或者如何将此 R 函数转换为 Rcpp?

x[!sapply(x, is.null)]

一些要测试的R数据:

x <- list("a"=1, "b"=NULL, "c"=NULL, "d"=2)
x <- list("b"=NULL, "c"=NULL)

到目前为止,这是我尝试过的: 第一个打破了 R & RStudio,第二个 returns 一个整数列表。

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

你可以做到

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