1

I have the following matrix:

        1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
   [1,] 0 0 0 0 0 0 0 0 0  0  0  1  0  0  0  0  1  0  0  0  0  0  0  0
   [2,] 0 0 0 0 0 0 0 0 0  1  0  0  0  0  0  1  0  0  0  0  0  0  0  1

My aim is thus: For each row in the matrix, I wish to print the column numbers where the value in the matrix is 1.

The following works, sort of:

for(l in 1:nrow(matrix))
{
print(which(matrix[l,]==1))
}

But returns the columns twice:

12 17

12 17

10 16 24

10 16 24

Is there a way to have the appropriate column numbers returned only a single time?

Sam Jones
  • 13
  • 1
  • 3

1 Answers1

4

You can try with apply by rows:

a<-c(0, 0 ,0 ,0 ,0, 0, 0, 0, 0 , 0 , 0,  1,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0 , 0)
b<-c(0, 0 ,0 ,1 ,0, 0, 0, 0, 0 , 1 , 0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  1 , 0)

matrix<-rbind(a,b,a)

apply(matrix,1 ,function(x) which(x==1))
dax90
  • 1,088
  • 14
  • 29
  • Thanks - this worked. When i initially tried your solution, the code continued to print two copies of each result (so i.e whereas your code in an empty R script would print the results once, mine would print it twice.) I removed the column names on my matrix and this solved the problem. Thank you. – Sam Jones Feb 12 '15 at 16:18