我有一个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")