Joh*_*nck 2 memory r matrix cumsum
在Python中我可以这样做:
a = np.arange(100)
print id(a) # shows some number
a[:] = np.cumsum(a)
print(id(a)) # shows the same number
Run Code Online (Sandbox Code Playgroud)
我在这里做的更换内容的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!
Run Code Online (Sandbox Code Playgroud)
问题是如何用计算结果覆盖R中已经分配的内存?当我在R与Rcpp中进行向量运算时(在C++中编写代码并从R调用它,这可以避免不必要的分配),缺少这种东西似乎会导致显着的性能差异.
我在Ubuntu Linux 10.04上使用R 3.1.1,具有24个物理内核和128 GB RAM.
试试这个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"
Run Code Online (Sandbox Code Playgroud)
需要注意的是,即使地址的A$a是参考更新后的不同,有没有复制在这里正在取得进展.它是不同的,因为它是一个完整的列plonk - 意味着向量cumsum(a)替换当前列a(通过引用).(你看到的地址cumsum(a)基本上是地址).