title: Union of intersecting vectors in a list in R
body: <p>I have a list of vectors as follows.</p>
  <pre><code>data &lt;- list(v1=c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;), v2=c(&quot;g&quot;, &quot;h&quot;, &quot;k&quot;), 
               v3=c(&quot;c&quot;, &quot;d&quot;), v4=c(&quot;n&quot;, &quot;a&quot;), v5=c(&quot;h&quot;, &quot;i&quot;))
  </code></pre>
  <p>I am trying to achieve the following:</p>
  <ol>
  <li>Check whether any of the vectors intersect with each other</li>
  <li>If intersecting vectors are found, get their union</li>
  </ol>
  <p>So the desired output is</p>
  <pre><code>out &lt;- list(v1=c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;n&quot;), v2=c(&quot;g&quot;, &quot;h&quot;, &quot;k&quot;, &quot;i&quot;))
  </code></pre>
  <p>I can get the union of a group of intersecting sets as follows.</p>
  <pre><code> Reduce(union, list(data[[1]], data[[3]], data[[4]]))
   Reduce(union, list(data[[2]], data[[5]])
  </code></pre>
  <p>How to first identify the intersecting vectors? Is there a way of dividing the list into lists of groups of intersecting vectors?</p>
  <p>#Update</p>
  <p>Here is an attempt using data.table. Gets the desired results. But still slow for large lists as in this <a href="http://ge.tt/4NI4CL72/v/1?c" rel="nofollow noreferrer">example</a> dataset.</p>
  <pre><code>datasets. 
  data &lt;- sapply(data, function(x) paste(x, collapse=&quot;, &quot;))
  data &lt;- as.data.frame(data, stringsAsFactors = F)
  
  repeat {
    M &lt;- nrow(data)
    data &lt;- data.table( data , key = &quot;data&quot; )
    data &lt;- data[ , list(dataelement = unique(unlist(strsplit(data , &quot;, &quot; )))), by = list(data)]
    data &lt;- data.table(data , key = &quot;dataelement&quot; )
    data &lt;- data[, list(data = paste0(sort(unique(unlist(strsplit(data, split=&quot;, &quot;)))), collapse=&quot;, &quot;)), by = &quot;dataelement&quot;]
    data$dataelement &lt;- NULL
    data &lt;- unique(data)
    N &lt;- nrow(data)
    if (M == N)
      break
  }
  
  data &lt;- strsplit(as.character(data$data) , &quot;,&quot; )
  </code></pre>