假设我有以下列表:
x <- list(a = c(1, 2), b = c("a", "c"), c = 1:10)
在 R 中,我可以使用以下两种方法删除第一个元素:
x[-1]
x[1] <- NULL
我正在尝试在 Rcpp 中做同样的事情,但我无法弄明白。以下代码只是将 NULL
分配给第一个元素。
// [[Rcpp::export]]
Rcpp::List removeElement(Rcpp::List x)
{
x[0] = R_NilValue;
return(x);
}
有什么想法吗?
最佳答案
怎么样
// [[Rcpp::export]]
Rcpp::List removeElement(Rcpp::List x, int j)
{
IntegerVector idx = seq_len(x.length());
return(x[idx != j]);
}
或者如果您希望索引从 0 开始使用
IntegerVector idx = seq_len(x.length()) - 1;
关于从 Rcpp 中的列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25881508/