title: R / Index lower triangle vector by pairwise indices
body: <p>I am looking for a way to index a lower triangle vector of a symmetric matrix by pairwise indices in the language <strong>R</strong>. Here is some explanatory code:</p>
  
  <h3>Background</h3>
  
  <p><code>M</code> is an <code>n</code> times <code>n</code> pairwise matrix, here with random data (just to show):</p>
  
  <pre><code>n &lt;- 5
  set.seed(0815)
  M &lt;- matrix(sample(n^2),n,n)
  M[upper.tri(M)] &lt;- t(M)[upper.tri(M)]
  diag(M) &lt;- 0
  M
  
  #      [,1] [,2] [,3] [,4] [,5]
  # [1,]    0    6    3   18   10
  # [2,]    6    0   11   23    9
  # [3,]    3   11    0    5   21
  # [4,]   18   23    5    0   16
  # [5,]   10    9   21   16    0
  </code></pre>
  
  <h3>Data</h3>
  
  <p>My data (<code>x</code>) is the lower triangle vector from the matrix <code>M</code>:</p>
  
  <pre><code>x &lt;- M[lower.tri(M)]
  </code></pre>
  
  <p>And the index pairs I want to extract is stored in a vector named <code>i</code>:</p>
  
  <pre><code>i &lt;- c(2:3,5)
  </code></pre>
  
  <h3>Aim</h3>
  
  <p>My aim is now to extract the pairs from the lower triangle vector as in the following matrix example. </p>
  
  <pre><code>aim &lt;- M[i,i][lower.tri(M[i,i])]
  aim
  # [1] 11  9 21
  </code></pre>
  
  <h3>My Solution</h3>
  
  <p>Since in my case <code>M</code> is not available and I don't want to generate it from <code>x</code> (memory issue), I created the following indexing function <code>f</code>:</p>
  
  <pre><code>f &lt;- function (n,i) {
    r &lt;- combn(i,2)[1,]
    c &lt;- combn(i,2)[2,]
    n * r + c - (r * (r + 1))/2 - n
  }
  </code></pre>
  
  <h3>The Result</h3>
  
  <pre><code>res &lt;- x[f(n,i)]
  identical(res, aim)
  # [1] TRUE
  </code></pre>
  
  <h3>Finally, my question:</h3>
  
  <p>Is there a <strong>more elegant</strong> or already <strong>builtin</strong> version in R of the function <code>f</code>, maybe one that also does not need <code>n</code> as argument, calculating it from the length of <code>x</code>?</p>
  
  <p>Thank you in advance.</p>
  
  <p>Sven</p>