Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column and row names of matrix indices in a vector

Tags:

r

vector

matrix

I have a 4x4 matrix and I want to identify elements of this matrix that are equal to a specific value such as 1. I want to save the indices of these elements as well as column and row names to two separate vectors. Finally, I want to write all of this information to a txt file.

I managed to get the indices to a txt file but I have no idea how to retrieve the column and row names from the matrix. To test, I am using following example:

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")
like image 761
wthimdh Avatar asked Feb 08 '23 15:02

wthimdh


1 Answers

The which function already provides a nice interface to getting all the row and column indices of a matrix that meet a certain criterion, using the arr.ind=TRUE argument. This is both much less typing and much more efficient than looping through each matrix element. For instance, if you wanted to get all the indices where your matrix equaled 5, you could use:

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

Now all that remains is a simple lookup using the row and column names of your matrix:

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

You could write this result out to a file using write.csv.

like image 100
josliber Avatar answered Feb 16 '23 03:02

josliber