gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:35:45 25 4
gpt4 key购买 nike

我有一个 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函数已经提供了一个很好的接口(interface)来获取矩阵的所有行和列索引,使用 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 将此结果写入文件。 .

关于r - 获取向量中矩阵索引的列名和行名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35715179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com