本文介绍了有没有一种方法可以防止在修改属性时进行修改时复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很惊讶用下面的代码制作了矩阵的副本:
I am surprised that a copy of the matrix is made in the following code:
> (m <- matrix(1:12, nrow = 3))
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> tracemem(m)
[1] "<000001E2FC1E03D0>"
> str(m)
int [1:3, 1:4] 1 2 3 4 5 6 7 8 9 10 ...
> attr(m, "dim") <- 4:3
tracemem[0x000001e2fc1e03d0 -> 0x000001e2fcb05008]:
> m
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> str(m)
int [1:4, 1:3] 1 2 3 4 5 6 7 8 9 10 ...
有用吗?可以避免吗?
我的结果与GKi不同.
I do not have the same results as GKi.
> sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)
Matrix products: default
locale:
[1] LC_COLLATE=French_France.1252 LC_CTYPE=French_France.1252 LC_MONETARY=French_France.1252
[4] LC_NUMERIC=C LC_TIME=French_France.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] compiler_4.0.3 tools_4.0.3
> m <- matrix(1:12, nrow = 3)
> tracemem(m)
[1] "<000001F8DB2C7D90>"
> attr(m, "dim") <- c(4, 3)
tracemem[0x000001f8db2c7d90 -> 0x000001f8db2d93f0]:
一个区别是我不使用BLAS库...
One difference is that I do not use BLAS library...
推荐答案
我正在使用R 3.6.3,实际上已经制作了一个副本.要更改属性而不进行复制,可以使用 data.table
包的 setattr
函数:
I'm using R 3.6.3 and indeed a copy is made. To change an attribute without making a copy, you can use the setattr
function of the data.table
package:
library(data.table)
m <- matrix(1:12, nrow = 3)
.Internal(inspect(m))
setattr(m, "dim", c(4L,3L))
.Internal(inspect(m))
这篇关于有没有一种方法可以防止在修改属性时进行修改时复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!