【发布时间】:2023-03-28 10:20:02
【问题描述】:
从Subsetting a large vector uses unnecessarily large amounts of memory继续:
给定一个原子向量,例如
x <- rep_len(1:10, 1e7)
如何修改 x 以使用 Rcpp 按数字索引删除元素?在 R 中,可以做到这一点,但不能就地(即不重复 x):
idrops <- c(5, 4, 9)
x <- x[-idrops]
一种相当有效的方法如下:
IntegerVector dropElements(IntegerVector x, IntegerVector inds) {
R_xlen_t n = x.length();
R_xlen_t ndrops = inds.length();
IntegerVector out = no_init(n - ndrops);
R_xlen_t k = 0; // index of out
for (R_xlen_t i = 0; i < n; ++i) {
bool drop = false;
for (R_xlen_t j = 0; j < ndrops; ++j) {
if (i == inds[j]) {
drop = true;
break;
}
}
if (drop) {
continue;
}
out[k] = x[i];
++k;
}
return out;
}
虽然这几乎没有到位(它也不是很安全,但那是无关紧要的)。我知道 STL 的 .erase(),但似乎 Rcpp 设计为在转换为 STL 之前制作了一个副本。
【问题讨论】:
-
那么,你想创建一个在内存中碎片化的过度分配的原子向量吗?我几乎可以肯定这是不可能的。
-
好的。也许问题应该是如何最小化操作的内存使用?
-
您的解决方案似乎是最小的 w.r.t.内存使用情况。
-
这取决于你看的片数。我的碎片很小,你可以使用一个类来保存对每个部分的索引引用和函数来循环索引。