title: R; replace nested for loop with apply() function
body: <p>I am working on data replacement in a matrix. The replaced data will be calculated by calculating the sd of the (1+2k)X(1+2k) matrix centered on the value.</p>
  <pre><code>replace.loop = function(n, m, k, pad){
    #search the value row by row, column by column 
    for (i in n) {
      for (j in m) {
        pad[i,j] = sd(as.vector(pad[(i-k):(i+k),(j-k):(j+k)]))
      }
    }
    return(pad) #return the matrix that finishing calculation
  }
  </code></pre>
  <p>Is there any way to rewrite this function with any apply() function? I am an R starter learner, so I am not sure which apply() function I should use.</p>
  <p>for example:</p>
  <pre><code>X = matrix(c(.5,.5,.4,.4,.3,.5,.5,.4,.3,.3,.4,.4,.3,.2,.2,.4,.4,.3,.2,.1,.3,.3,.2,.2,.1), ncol=5)
  k = 1
  pad.X = matrix(0, dim(X)[1]+2*k, dim(X)[2]+2*k)
  n = (k+1):(dim(X)[1]+k);  m = (k+1):(dim(X)[2]+k)
  pad.X[n, m] = X
  
  </code></pre>
  <p>Thanks!</p>