在Python中我可以这样做:
a = np.arange(100)
print id(a) # shows some number
a[:] = np.cumsum(a)
print(id(a)) # shows the same number
我在这里所做的是替换contents of a
与它的 cumsum。前后的地址是一样的。
现在让我们在 R 中尝试一下:
install.packages('pryr')
library(pryr)
a = 0:99
print(address(a)) # shows some number
a[1:length(a)] = cumsum(a)
print(address(a)) # shows a different number!
问题是如何用计算结果覆盖 R 中已分配的内存?当我在 R 与 Rcpp 中进行向量运算时,缺乏此类东西似乎会导致显着的性能差异(用 C++ 编写代码并从 R 调用它,这让我可以避免不必要的分配)。
我在 Ubuntu Linux 10.04 上使用 R 3.1.1,具有 24 个物理内核和 128 GB RAM。
Try the data.table
包裹。它允许更新值引用使用:=
运算符(以及使用函数set
):
library(data.table)
A <- data.table(a = seq_len(99))
address(A) # [1] "0x108d283f0"
address(A$a) # [1] "0x108e548a0"
options(datatable.verbose=TRUE)
A[, a := cumsum(a)]
# Detected that j uses these columns: a
# Assigning to all 99 rows
# Direct plonk of unnamed RHS, no copy. <~~~ no copy of `A` or `A$a` is made.
address(A) # [1] "0x108d283f0"
address(A$a) # [1] "0x1078f5070"
请注意,即使address of A$a
通过引用更新后有所不同,有no copy正在这里制作。它是不同的,因为它是一个完整的列 plonk - 意思是向量cumsum(a)
替换当前列a
(引用)。 (你看到的地址是cumsum(a)
基本上)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)