我正在R
中编写一个邻接矩阵,如下所示:
neighbours <- array(0, c(100,100))
for (i in 1:100) { neighbours[i,i] = 1 } #reflexive
但是后来我注意到
class(neighbours)
是double matrix
。对于较大的矩阵,这将占用太多空间。因此,我想将类型强制为integer
,或者甚至更好,因为这是无向的logical
。但...
> class(neighbours[5])
[1] "numeric"
> class(neighbours[5]) <- "integer"
> class(neighbours[5])
[1] "numeric"
不听我说!
最佳答案
最好不要首先将其初始化为数字,但是如果您不能这样做,请设置storage.mode
:
R> neighbours <- array(0, c(100,100))
R> for (i in 1:100) { neighbours[i,i] = 1 }
R> str(neighbours)
num [1:100, 1:100] 1 0 0 0 0 0 0 0 0 0 ...
R> storage.mode(neighbours) <- "integer"
R> str(neighbours)
int [1:100, 1:100] 1 0 0 0 0 0 0 0 0 0 ...
R> storage.mode(neighbours) <- "logical"
R> str(neighbours)
logi [1:100, 1:100] TRUE FALSE FALSE FALSE FALSE FALSE ...