I have a matrix table where rows indicate a site, and columns indicate the presence/absence of a particular rock.
>Mat
A B C D E F G
Aiz 1 0 0 0 0 0 0
Aren 0 1 1 0 1 0 0
Atx 0 0 1 0 1 0 0
Berr 1 1 0 0 0 1 0
Bra 0 0 0 0 0 1 0
Bur 0 1 0 0 1 0 0
Cab 1 0 1 1 1 0 0
As you can see, there are some rows that have the same elements in certain columns, eg. row Aiz and row Berr, share a presence in column A, which indicates me that they share one same rock in my example.
From this matrix I want to construct and undirected graph where the nodes are the sites (the rownames) and the links are the share of an element of a column.
So, basically, I need to transform this matrix into a data.frame of the style:
>DF
siteA siteB weight
1 Aiz Berr 1
2 Aiz Cab 1
3 Aren Atxos 2
4 Aren Berr 1
5 Aren Bur 2
6 Aren Cab 1
7 Atx Bur 1
...
Where each row identifies two sites that share a same rock (presence in a same column of original Mat) and with column weight, representing the number of rocks that both sites have in common.
So, through a series of nested for loops, and if conditions, I manage to arrive close to the DF matrix, although my DF has rows with repeated results, eg:
> df_links
siteA siteB weight
1 Aiz Berr 1
2 Aiz Cab 1
3 Aren Atxos 2
4 Berr Aiz 1
5 Atxos Aren 2
where you see, eg: row 1 and row 4 (same for row 3 and row 5) share the same elements for the site columns. And since this is for an undirected graph, having Aiz- Berr or Ber - Aiz would mean the same, therefore I would only need one of the rows.
Q 1: So, I tried to solve the repetition problem with tidyverse, but nothing seemed to work. At best I would get rid of only one of the repeating rows and not all. So, my question is, is there a way where I can do this? To retain only one of the rows that have the same elements [i,j], regardless of order?
Q 2: this might be a bit more cumbersome, so it comes in second. Even though my code works (until the problem pointed above in Q1), its not the prettiest to look at. Is a sequence of matrix to data.frames to data.frames with for loops, and conditions trown in.
Is there a tiddier version to go from the original Mat to the desired DF?? I´m not that well versed in sapply and the whole family, so I used the loops. Any quicker and better looking solution?