r - 无法将矩阵数类强制为整数

标签 r oop class matrix

我在 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/

相关文章:

objective-c - 我应该在我自己的代码之后还是之前调用 [super superMethod]?

php - 如何创建带有可选参数的构造函数?

javascript - 在 JavaScript 中使用 Array 对象在数组内部的实例上调用任意方法

c++ - 将对象数组、对象的数量和所需的术语传递给函数

python - 如何使用类在列表中查找总和

r - 如何使 R 中绘制的圆更小?

r - 由特定变量进行分面包裹 + ggplot2 + r

r - 将一组函数应用于对象

jquery - 如何使用JQuery触发Shiny中触发observeEvent的按钮点击?

php - Doctrine 1.2 自动加入 i18n?