Savi
Savi

Reputation: 51

How to retrieve the column index for every row that has a particular value in R?

I have the matrix below:

x=
1 0 1 1  
0 1 0 0  
1 0 0 0  

I need to retrieve the following values (corresponding to column indices):

My real data is a matrix of 300X66,000.

Upvotes: 2

Views: 98

Answers (1)

akrun
akrun

Reputation: 886948

We could create a logical index and use which with arr.ind=TRUE to get row/column index. It may be better to store it as such. We could also split the 'indx' to a 'list'.

indx <- which(X!=0, arr.ind=TRUE)
split(indx[,2], indx[,1])
#$`1`
#[1] 1 3 4

#$`2`
#[1] 2

#$`3`
#[1] 1

Or use apply with MARGIN=1

apply(!!X, 1, which)

Upvotes: 2

Related Questions