title: Constructing functions in R within a for loop
body: <p>I have been trouble-shooting my code, but am stuck. I am trying to run a function repeatedly in a for loop in R, while appending to a vector. My code is as follows:</p>
  
  <pre><code>densities = rep(NA, length(seq(0, 1, by = 0.01)))
  count = 1
  
  for (t in seq(0, 1, by = 0.01)) {
    applyThreshold(t, densities, count)
  }
  
  applyThreshold = function(t, densities, count){
    tMatrix = corMatrix
    tMatrix[corMatrix &lt; t] = 0 
    tMatrix[corMatrix &gt;= t] = 1
    nVector = c()
    for (n in 1:dim(tMatrix)[1]){
      nSum = sum(tMatrix[,n])
      if (nSum == 0){
        nVector = c(nVector, n)
      }
    }
    if (length(nVector) &gt;0){
      tMatrix = tMatrix[,-(nVector)]
      tMatrix = tMatrix[-(nVector),] 
    }
  
    E = sum(tMatrix)/2
    V = dim(tMatrix)[1]
    densities[count] = 2*E/(V*(V-1))
    count = count + 1
  }
  </code></pre>
  
  <p>At the end of running this command, though, my densities and count have not updated. I have a feeling this is a simple fix, but I have been looking at the documentation for functions in R, and am still stuck. Any advice would be appreciated!</p>