Apply a function to all pairwise combinations of list elements in R
<p>I want to apply a function to all pairwise combinations of list elements.
Each element is a vector with the same length. I would like the output in a <code>n x n</code> matrix format, <code>n</code> being the number of elements in my list. </p>

<p>Consider the following example:</p>

<pre><code># Generating data
l &lt;- list()
for(i in 1:5) l[[i]] &lt;- sample(0:9, 5, T)

# Function to apply
foo &lt;- function(x, y) 1 - sum(x * y) / sqrt(sum(x ^ 2) * sum(y ^ 2))

# Generating combinations
comb &lt;- expand.grid(x = 1:5, y = 1:5)
</code></pre>

<p>This loop works but it is slow and the output is not formatted as a matrix</p>

<pre><code># Applying function
out &lt;- list()
for(i in 1:nrow(comb)) {
  out[[i]] &lt;- foo(l[[comb[i, 'x']]], l[[comb[i, 'y']]])
}
</code></pre>

<p>Any idea?</p>