title: Using loop to create network group is not efficient
body: <p>I have a data frame with 100 columns but this operation require only two column. I am keeping only tow columns like this:</p>
  <pre><code>org &lt;- data.frame(
    ID = c( &quot;ID1&quot;, &quot;ID2&quot;, &quot;ID3&quot;, &quot;ID4&quot;, &quot;ID5&quot;, &quot;ID1&quot;, &quot;ID2&quot;,
             &quot;ID1&quot;, &quot;ID2&quot;, &quot;ID1&quot;, &quot;ID2&quot;, &quot;ID1&quot;, &quot;ID2&quot;, &quot;ID3&quot;,
             &quot;ID1&quot;, &quot;ID5&quot;, &quot;ID1&quot;, &quot;ID2&quot;, &quot;ID1&quot;, &quot;ID2&quot;, &quot;ID3&quot;),
    
    Key = c(1, 2, 3, 5, 7, 1, 2, 1, 8, 3, 9, 4,
             11, 15, 4, 17, 11, 15, 17, 4, 18)
  )
  </code></pre>
  <p>Notice that &quot;ID1&quot; is assigned to keys 1, 3, 4, 11, and 17. So this keys are in a group1 <br/>
  Here &quot;3&quot; is the key for ID3 also. <br/>
  And ID3 has key &quot;15&quot; and &quot;18&quot;. Thus &quot;15&quot; and &quot;18&quot; will also be in the same group as 1, 3, 4, 11, 17, 15, 18. The association of &quot;ID&quot;s to key (vice versa : key to ID ) is not unique. <br/>
  I want to find the all the groups and their keys. <br/>
  I found a solution on <a href="https://stackoverflow.com/a/69324113/14227528">my previous question</a> as :</p>
  <pre><code>t &lt;- table(org$ID_id,org$key)
  
  new_group &lt;- list()
  
  for (i in rownames(t)) {
    row_values &lt;- names(t[i,][t[i,]&gt;0])
    
    if(length(new_group)==0){
      new_group[[i]] &lt;- row_values # add first key values to group 1
    } else{
      create_new_group &lt;- TRUE
      for (list_item in seq_len(length(new_group))) {
        if(max(row_values %in% new_group[[list_item]]) == 1){# If key values (some or all) exist in current group
          new_group[[list_item]] &lt;- unique(c(new_group[[list_item]],  row_values))
          create_new_group &lt;- FALSE
        }
      }
      if(create_new_group){
        new_group[[length(new_group)+1]] &lt;- row_values
      }
    }
    
  }
  </code></pre>
  <p>This works great. However, my data frame has 8 millions of observation and this is not efficient. I would appreciate any help on making this code efficient.</p>