Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Rcpp中的列表中删除元素_R_Rcpp - Fatal编程技术网

从Rcpp中的列表中删除元素

从Rcpp中的列表中删除元素,r,rcpp,R,Rcpp,假设我有以下列表: x <- list(a = c(1, 2), b = c("a", "c"), c = 1:10) 有什么想法吗?怎么样 // [[Rcpp::export]] Rcpp::List removeElement(Rcpp::List x, int j) { IntegerVector idx = seq_len(x.length()); return(x[idx != j]); } 或者,如果希望索引从0开始,请使用 IntegerVector idx =

假设我有以下列表:

x <- list(a = c(1, 2), b = c("a", "c"), c = 1:10)
有什么想法吗?

怎么样

// [[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;

谢谢你的回复。我不知道我们可以使用
x[idx!=j]
。对于我的问题,我正在寻找一个更普遍的解决方案。我想使用if-else语句确定函数中的
j
,可能需要删除许多元素。例如,我可能希望删除所有长度为2的列表元素。使用
x[!sappy(x,!islengththow)]
,其中
islengththow
是一个函数,它接受
SEXP
并返回
bool
。或者,一般来说,您可以使用
x[sapply(x,f)]
来选择某些函数/函子。您现在只选择长度为2的元素,Kevin;-)我用答案解决了我的问题。使用循环,我从末尾一个接一个地删除元素@KevinUshey感谢您的投入。我相信你的回答很笼统。。
// [[Rcpp::export]]
Rcpp::List removeElement(Rcpp::List x, int j)
{
  IntegerVector idx = seq_len(x.length());
  return(x[idx != j]);
}
IntegerVector idx = seq_len(x.length()) - 1;