Как я могу удалить элементы NULL из простого списка, используя Rcpp
?
Или как я могу перевести эту 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, а второй возвращает список целых чисел.
#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]);
}