title: A for loop with rowSums function
body: <p>I am a beginner in R and I have written a double-for loop for calculating chi2 values for selecting features among 6610 terms and 10 classes.
  Here is my for loops:</p>
  
  <pre><code>library(raster)
    #for x^2 [n,r] = term n, class r. n starts from col #7 and r starts from col #6617
  
    chi2vals &lt;- matrix(0:0,6610,10)
    chi2avgs &lt;- vector("numeric",6610L)
  
    for(r in 1:10){
      for(n in 1:6610){
  
        A = sum(data1.sub.added[,6+n]==1 &amp; data1.sub.added[,6616+r]==1)
        M = sum(data1.sub.added[,6+n]==1)
        P = sum(data1.sub.added[,6616+r]==1)
        N = nrow(data1.sub.added)
        E = ((A*N)-(M*P))**2
        F = (N-P)*(N-M)
        chi2vals[n,r] = (N/(P*M))*(E/F) # for term n
      }
  
      Prcj = sum(data1.sub.added[,6616+r]==1)/sum(data1.sub.added[,6616:6626]==1) #probability of class c_r
      pchi &lt;- Prcj * chi2vals
      chi2avgs[n] = rowSums(pchi)[n]
    }
  </code></pre>
  
  <p>The code correctly calculates everything up to the line <code>pchi &lt;- Prcj * chi2vals</code>. The result is a nice matrix of p*chi2 values:</p>
  
  <pre><code>&gt; head(pchi)
               [,1]        [,2]         [,3]      [,4]       [,5]         [,6]       [,7]        [,8]         [,9]
  [1,] 128.36551442 0.239308113  0.683517530 1.5038665  0.6145058 3.656857e-01  1.3311564   2.6977448  0.410702803
  [2,]   0.06632758 0.067970859  0.019178551 0.2900692  1.5300639 4.430705e-08  0.2599859   0.6362953  0.098745147
  [3,]   1.85641330 1.411925435  3.590747764 7.3018416 38.8044465 4.102248e-01  6.4118078  13.0164994  1.709506238
  [4,]   0.11063892 0.005039029  0.244964758 0.1622654  0.1156411 8.274468e+00  0.2564959   0.0577651  0.242946022
  [5,]   0.04788648 0.049072885  0.001420669 0.2094211  1.7200152 2.045923e-01  0.1877019   0.1468187  0.005493183
  [6,]   5.39946188 6.899336618 60.735646913 7.4351538 10.7005784 9.946261e+00 35.8868899 178.7112406 11.382740754
             [,10]
  [1,]  0.26436516
  [2,]  0.14414444
  [3,]  0.90292073
  [4,]  0.01168997
  [5,]  0.06641298
  [6,] 19.68599142
  </code></pre>
  
  <p>But the final <code>chi2avgs</code> values mostly turn out to be zeros:</p>
  
  <pre><code>&gt; head(chi2avgs)
  [1] 0.000000   0.000000   0.000000   0.000000   2.638835   0.000000
  </code></pre>
  
  <p>However, when aside from the loop I replace n with any number, the last line works well:</p>
  
  <pre><code>  chi2avgs[1] = rowSums(pchi)[1]
    chi2avgs[2] = rowSums(pchi)[2]
    chi2avgs[3] = rowSums(pchi)[3]
    chi2avgs[4] = rowSums(pchi)[4]
    chi2avgs[5] = rowSums(pchi)[5]
  
  &gt; head(chi2avgs)
  [1] 136.476367   3.112781  75.416334   9.481914   2.638835   0.000000
  </code></pre>
  
  <p>I wonder what causes this problem. Do you have an idea how I can fix it?</p>