繁体   English   中英

获取向量中矩阵索引的列名和行名

[英]Get column and row names of matrix indices in a vector

我有一个4x4矩阵,我想标识该矩阵中等于特定值(例如1)的元素。我想将这些元素的索引以及列名和行名保存到两个单独的向量中。 最后,我想将所有这些信息写入txt文件。

我设法将索引获取到txt文件,但是我不知道如何从矩阵中检索列名和行名。 为了测试,我使用以下示例:

mat <- matrix(c(1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6), ncol=4, nrow=4)
colnames(mat) <- c("C1","C2","C3","C4")
rownames(mat) <- c("R1", "R2","R3","R4")

r.indices <- c()
c.indices <- c()
for (row in 1:nrow(mat)){
    for (col in 1:(ncol(mat)-row+1)){

        if (mat[row,col] == cutoff){
            #print("this is one!")
            r.indices <- c(r.indices,row)
            c.indices <- c(c.indices,col)
        }

     }
}


write.csv(cbind(r.indices, c.indices), file="data.txt")

which函数已经提供了一个不错的接口,可以使用arr.ind=TRUE参数来获取满足特定条件的矩阵的所有行索引和列索引。 与遍历每个矩阵元素相比,这不仅打字少而且效率更高。 例如,如果要获取矩阵等于5的所有索引,则可以使用:

(idx <- which(mat == 5, arr.ind=TRUE))
#    row col
# R1   1   2
# R3   3   4

现在剩下的就是使用矩阵的行和列名称的简单查找:

cbind(rownames(mat)[idx[,"row"]], colnames(mat)[idx[,"col"]])
#      [,1] [,2]
# [1,] "R1" "C2"
# [2,] "R3" "C4"

您可以使用write.csv将结果写到文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM