关于矩阵:如何处理R中矩阵的无穷大?

How does one handle infinite values in matrices in R?

我有一个矩阵,我怀疑它包含一些无限元素。

我有两个问题:

  • 是否存在像sum(is.na)这样的等效计数函数,该函数为我提供了矩阵中无穷大的数量?
  • 我想计算矩阵的每一行与另一个向量的点积。如何忽略无穷大的值?求和函数中类似na.rm = T函数的东西。
  • 谢谢


    尝试此操作,但请确保您的输入数据属于类矩阵:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    set.seed(1)

    # make data
    n <- 20
    m <- 10
    M <- matrix(rnorm(n*m), n, m)

    # add Infs
    M[sample(x = length(M), size = length(M)*0.1)] <- Inf
    image(seq(n), seq(m), M, xlab ="rows", ylab ="columns")

    # here is the vector that you want to multiply each row with
    multVec <- seq(m)

    # apply with removal of non-finite values
    res <- apply(M, 1, function(x){
      tmp <- x * multVec
      sum(tmp[is.finite(tmp)])
    })