Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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
......
like image 713
ToToRo Avatar asked Dec 30 '25 14:12

ToToRo


1 Answers

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))
like image 157
flodel Avatar answered Jan 02 '26 04:01

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!