Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a general solution, similar in spirit to that of @Ramnath, but avoiding the use of <code>union()</code> which is a binary function. The trick is to note that <code>union()</code> is implemented as:</p> <pre><code>unique(c(as.vector(x), as.vector(y))) </code></pre> <p>and the bit inside <code>unique()</code> can be achieved by unlisting the <code>n</code>th component of each list.</p> <p>The full solution then is:</p> <pre><code>unionFun &lt;- function(n, obj) { unique(unlist(lapply(obj, `[[`, n))) } lapply(seq_along(lst[[1]]), FUN = unionFun, obj = lst) </code></pre> <p>which gives:</p> <pre><code>[[1]] [1] 1 2 3 4 5 6 7 8 9 10 11 12 [[2]] [1] 6 7 8 9 10 11 1 2 3 4 5 12 </code></pre> <p>on the data you showed.</p> <p>A couple of useful features of this are:</p> <ul> <li>we use <code>`[[`</code> to subset <code>obj</code> in <code>unionFun</code>. This is similar to <code>function(x) x$a</code> in @Ramnath's Answer. However, we don't need an anonymous function (we use <code>`[[`</code> instead). The equivalent to @Ramnath's Answer is: <code>lapply(lst, `[[`, 1)</code></li> <li>to generalise the above, we replace the <code>1</code> above with <code>n</code> in <code>unionFun()</code>, and allow our list to be passed in as argument <code>obj</code>.</li> </ul> <p>Now that we have a function that will provide the union of the <code>n</code>th elements of a given list, we can <code>lapply()</code> over the indices <code>k</code>, applying our <code>unionFun()</code> to each sub-element of <code>lst</code>, using the fact that the length of <code>lst[[1]]</code> is the same as <code>length(lst[[k]])</code> for all <code>k</code>.</p> <p>If it helps to have the names of the <code>n</code>th elements in the returned object, we can do:</p> <pre><code>&gt; unions &lt;- lapply(seq_along(lst[[1]]), FUN = unionFun, obj = lst) &gt; names(unions) &lt;- names(lst[[1]]) &gt; unions $a [1] 1 2 3 4 5 6 7 8 9 10 11 12 $b [1] 6 7 8 9 10 11 1 2 3 4 5 12 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload