ToToRo
ToToRo

Reputation: 373

R: how can I get the Row sequential ID when the number appears again?

For instance, I have a data frame like this, there is no duplicated number for each row, numbers are sorted by each row.

  W1 W2 W3 W4
1  1  3  4  7
2  4  5  6  7
3  1  2  5  8
4  2  5  9  10
5  4  7  10 13
6  1  2  6  9 

I want to get the row ID when 1/2/3.... appears, since 1 in row 1,3,6; 2 in row 3,4,6; 3 in row 1 only, ...; So my result would like this

1  1 3 6
2  3 4 6 
3  1 
4  1 2 5
5  2 3 4
......

Upvotes: 3

Views: 58

Answers (1)

flodel
flodel

Reputation: 89107

I would do:

split(t(row(df)), unlist(t(df)))

And if you need empty levels to show up:

split(t(row(df)), factor(unlist(t(df)), 1:max(df)))

This should be a lot faster than looping via for example:

lapply(1:max(df), function(i) which(rowSums(df == i) > 0))

Upvotes: 3

Related Questions