0

所以我有一个我正在循环的矩阵 TMatrix,我想将每个包含非有限值的单元格的行名和列名放入表中。我尝试执行以下操作,但我不断获得行名和列名的 NA 。这是怎么回事?

    AA <- 1:rowlength
    BB <- 1:ncol(Nmatrix)
    for(i in AA){
        for(j in BB){
            if (is.finite(TMatrix[i,j])==FALSE){
                TNS <- matrix(data=NA,nrow=1,ncol=4)
                TNS[1,1] <- TMatrix[i,j]
                TNS[1,2] <- Nmatrix[i,j]
                TNS[1,3] <- paste(rownames(TMatrix)[TMatrix[i,j]])
                TNS[1,4] <- paste(colnames(TMatrix)[TMatrix[i,j]])
                TMinf <- rbind(TMinf,TNS)
            }
            PMatrix[i,j] <- pt(TMatrix[i,j],n1+n2-2)
        }
    }
4

2 回答 2

1

不知道这是在做什么,因为您提供了零个我们需要运行它的对象,但听起来您想要在以下示例中执行某些操作:

mat <- matrix(rnorm(20), nrow = 4)
mat[1, 4] <- mat[3, 2] <- NA


#             [,1]      [,2]       [,3]       [,4]       [,5]
# [1,]  0.11025848 1.1021023 -0.3098129         NA -0.1358902
# [2,]  0.00351275 0.1440906  1.2141437  0.2601651  0.2504035
# [3,] -1.11565805        NA  0.1483867 -0.4102958 -0.3104319
# [4,]  0.34785864 1.5319365  1.2750632  0.1259548 -0.7594117

which(!is.finite(mat), arr.ind = TRUE)

#      row col
# [1,]   3   2
# [2,]   1   4

如果您有名为的行/列:

colnames(mat) <- LETTERS[1:5]
rownames(mat) <- letters[1:4]

#             A         B          C          D          E
# a  0.11025848 1.1021023 -0.3098129         NA -0.1358902
# b  0.00351275 0.1440906  1.2141437  0.2601651  0.2504035
# c -1.11565805        NA  0.1483867 -0.4102958 -0.3104319
# d  0.34785864 1.5319365  1.2750632  0.1259548 -0.7594117

idx <- which(!is.finite(mat), arr.ind = TRUE)

rownames(mat)[idx[ , 'row']]
# [1] "c" "a"

colnames(mat)[idx[ , 'col']]
# [1] "B" "D"
于 2014-02-23T21:53:16.987 回答
0

没关系,我想通了。我的索引错了。它应该是这样的:

AA <- 1:rowlength
BB <- 1:ncol(Nmatrix)
for(i in AA){
    for(j in BB){
        if (is.finite(TMatrix[i,j])==FALSE){
            TNS <- matrix(data=NA,nrow=1,ncol=4)
            TNS[1,1] <- TMatrix[i,j]
            TNS[1,2] <- Nmatrix[i,j]
            TNS[1,3] <- rownames(TMatrix)[i]
            TNS[1,4] <- colnames(TMatrix)[j]
            TMinf <- rbind(TMinf,TNS)
        }
        PMatrix[i,j] <- pt(TMatrix[i,j],n1+n2-2)
    }
}
于 2014-02-23T21:49:27.017 回答