title: Change value in matrix using defined function in R
body: <p>I am still new to R.
  I was wondering how to use self-defined function to change elements in matrix.
  Say, I have a matrix "test"<br><code>test = matrix(c(1:9), 3, 3)</code><br>
  and I wrote a function "testFunction" to add each element by 20.<br></p>
  
  <pre><code>testFunction = function(){
    for(i in rownames(test)){
      for(j in colnames(test)){
        test[i,j] = test[i,j] + 20
      }
    }
  }
  </code></pre>
  
  <p>If I do it manually, such as <code>test[1,1] = test[1,1] + 20</code>, it works.<br>
  But if I use the function I wrote, the matrix remain the same.
  The "test" matrix after running the "testFunction" is still</p>
  
  <pre><code>         [,1] [,2] [,3]
  [1,]    1    4    7
  [2,]    2    5    8
  [3,]    3    6    9
  </code></pre>
  
  <p>Does anyone know why? And how can I change the values in the matrix using functions?
  Thanks.</p>
  
  <p><strong>Update</strong><br>
  So, actually I am creating a 452*452 matrix "pairMatrix" and a function "countPair"</p>
  
  <pre><code>pairMatrix = matrix(0, 452,452)
  rownames(pairMatrix) = players
  colnames(pairMatrix) = players
  </code></pre>
  
  <p>and 
  I will pass a data frame to the function, and the function will loop through each row to find "Player1" and "Player2". Then, using these two values as row name and column name to find the element in the pairMatrix and add by 1.</p>
  
  <pre><code>countPair = function(someDataFrame, pairMatrix){
    for (i in rownames(someDataFrame)){
      w = someDataFrame[i,"Player1"]
      l = someDataFrame[i,"Player2"]
      pairMatrix[w,l] = pairMatrix[w,l] + 1
      pairMatrix[l,w] = pairMatrix[l,w] + 1
    }
    return(pairMatrix)
  }
  </code></pre>
  
  <p>However, though the simple test case now works by following the suggestion, this complicated case does not work.
  Any suggestion?
  Thanks.</p>