So I have a matrix TMatrix that i'm cycling through, and I want to put the row and column names for every cell that contains a value that is not finite into a table. I've tried to doing the following, but I keep getting NA for the row and column names. What's going on?

    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)
        }
    }
有帮助吗?

解决方案 2

Never mind, I figured it out. I had the index wrong. It should be like this:

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)
    }
}

其他提示

No idea what this is doing because you provided zero of the objects we would need to run this, but it sounds like you are wanting to do something in the following example:

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

If you have the rows/columns named:

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"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top