我在 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 ...
关于r - 无法将矩阵数类强制为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12326366/