关于 (i,j) 中不存在的 NA 的 sparseMatrix 调用错误

问题描述 投票:0回答:1

我正在使用 R 包中的函数

sparseMatrix
Matrix

library(Matrix)
sparseMatrix(graph$src, graph$dst, x = 1, dims = c(29, 29))

在这里,

graph
是一个数据框,包含名为
src
dst
的因素,每个因素有 29 个级别。评估上述调用会导致此错误:

Error in sparseMatrix(graph$src, graph$dst, x = 1, dims = c(29,  : 
  NA's in (i,j) are not allowed

但事实是

graph$src
graph$dst
都不包含
NA
。为什么我会看到这个错误?我该如何解决?

r sparse-matrix
1个回答
0
投票

错误消息表明您使用的是 Matrix 版本 1.5-1 或更早版本。 1.5-2 版本修复了函数

sparseMatrix
中的几个错误。值得注意的是,它曾经这样做过:

    i <- as.integer(i + !(m.i || i1))
    j <- as.integer(j + !(m.j || i1))

具有用等长但完全由

i
组成的整数向量替换因子
j
NA
的效果。现在它这样做:

    if(!m.i)
        i <- if(index1) as.integer(i) - 1L else as.integer(i) # need 0-index
    if(!m.j)
        j <- if(index1) as.integer(j) - 1L else as.integer(j) # need 0-index

强制转换为整数first以便以合理的方式处理因素。

因此你应该简单地更新Matrix

update.packages("Matrix")

或者,如果由于某种原因这是不可能的,强制自己整数:

sparseMatrix(as.integer(graph$src), as.integer(graph$dst), x = 1, dims = c(29, 29))
© www.soinside.com 2019 - 2024. All rights reserved.