Home > Software engineering >  For each row return the multiple column indexs for specific number
For each row return the multiple column indexs for specific number

Time:11-10

Hi suppose I have a matrix with 0 an 1 only and I want to find out where 1 locates in each row. And for each row, there are multiple 1 exist. For example I have

set.seed(444)
m3 <- matrix(round(runif(8*8)), 8,8)

For the first row I have column 2,3,8 are 1 and I want a code could report either column name or column index. Meanwhile, it is worth to point out that each the number of 1 in each row could be different.

Can anyone provide some suggestions? I appreciate it so much.

CodePudding user response:

We can use which with arr.ind which returns the row/column index as a matrix

out <- which(m3 ==1, arr.ind = TRUE)
out[,2][order(out[,1])]
[1] 2 3 8 3 5 3 4 8 7 4 6 7 1 3 4 6 1 4 5 6 7 2 4 7 8

To get the column name, use the same index (if the matrix have any column names- here there are not column names attribute)

colnames(m3)[out[,2][order(out[,1])]]
  •  Tags:  
  • r
  • Related