I have a matrix similar to the one below, but more.
vec <- c(0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0) M <- matrix(vec, nrow = 4, byrow = TRUE) colnames(M) <- rownames(M) <- LETTERS[1:4] A, B, C, D A, 0, 1, 1, 0 B, 0, 0, 1, 1 C, 1, 0, 0, 0 D, 0, 1, 1, 0
Ultimately, I need a matrix or data.frame, where every time a call in a row matters, I get the name rowname, the name of the column. So, given the matrix above, I end up with a matrix or data frame below:
A,B A,C B,C B,D C,A D,B D,C
I can do this with loops and with expand.grid, but this is similar to what I have to do with apply functions. For example, I can get part of the path as follows:
tmp <- apply(M, 1, function(x) colnames(M)[which(x > 0)])
which gives me
$A [1] "B" "C" $B [1] "C" "D" $C [1] "A" $D [1] "B" "C"
If this is easy, can I also include the number in the cell (for cells over 0) as the third column?