title: Loop over rows within ifelse in R
body: <p>I have a dataframe, dt with two variables as given below. Using the code below, I want to get matrix G.</p>
  <pre><code>V1   V2
  1   60
  1   30
  1   38
  1   46
  2   29
  2   35
  2   13
  2   82
  3   100
  3   72
  3   63
  3   45
  </code></pre>
  <p>Code is:</p>
  <pre><code>l1 &lt;- seq(1, 3, 1)
  G&lt;-matrix(data=0, nrow=3, ncol=3)
  for (m in seq_along(l1)){
    for (n in seq_along(l1)){
      G[m,n]=sum(apply(dt,1,function (y) {ifelse(dt$V2[dt$V1==m]&lt;dt$V2[dt$V1==n] ,1,0)}))
    }
  }
  </code></pre>
  <p>What I get as G:</p>
  <pre><code>     [,1] [,2] [,3]
  [1,]    0   24   36
  [2,]   24    0   36
  [3,]   12   12    0
  </code></pre>
  <p>What I want as G:</p>
  <pre><code>     [,1] [,2] [,3]
  [1,]    0    5   14
  [2,]    5    0   13
  [3,]   14   13    0
  </code></pre>
  <p>Basically, for V1=1 we want to compare all values of V2 with all values of V2 for V1= 2 and 3. Repeat the same for V2 and V3.</p>
  <pre><code>For V1=1-&gt;
  ( 60 &gt; 29 : loop returns 0,
  60 &gt; 35 : loop returns 0,
  60 &gt; 13 : loop returns 0,
  60 &lt; 82 : loop returns 1,
  30 &gt; 29 : loop returns 0,
  30 &lt; 35 : loop returns 1,
  30 &gt; 13 : loop returns 0,
  30 &lt; 82 : loop returns 1,
  38 &gt; 29 : loop returns 0,
  38 &gt; 35 : loop returns 0,
  38 &gt; 13 : loop returns 0,
  38 &lt; 82 : loop returns 1,
  46 &gt; 29 : loop returns 0,
  46 &gt; 35 : loop returns 0,
  46 &gt; 13 : loop returns 0,
  30 &lt; 82 : loop returns 1)=Sum is 5 (i.e. G[1,2])
  </code></pre>
  <p>How can I revise the code to get the desired output?</p>