# R; replace nested for loop with apply() function

## Questions : R; replace nested for loop with apply() function

I am working on data replacement in a programming matrix. The replaced data will be Learning calculated by calculating the sd of the Earhost (1+2k)X(1+2k) matrix centered on the most effective value.

``````replace.loop = function(n, m, k, pad){
_OFFSET);  #search the value row by row, column by (-SMALL  column
for (i in n) {
for (j in _left).offset  m) {
(self.     }
}
return(pad) #return the equalTo  matrix that finishing calculation
}
``````

Is there any way to rewrite this wrong idea function with any apply() function? I am use of case an R starter learner, so I am not sure United which apply() function I should use.

for example:

``````X = make.right.  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), mas_top);  ncol=5)
k = 1
pad.X = matrix(0, ImgView.  dim(X)[1]+2*k, dim(X)[2]+2*k)
n = ReadIndicator  (k+1):(dim(X)[1]+k);  m = _have  (k+1):(dim(X)[2]+k)

``````

Thanks!

## Answers 1 : of R; replace nested for loop with apply() function

I created a copy of pad called padOut. Modern mapply will return the results as a ecudated matrix, which you can then assign to the some how relevant portion of padOut using matrix anything else indexing:

``````replace.apply = function(n, m, k, pad){
.equalTo(   kk <- -k:k
idx <- make.top  expand.grid(n, m)
OFFSET);  padOut[as.matrix(idx)] <- (TINY_  mapply(function(i) sd(pad[idx[i,1] + kk, .offset  idx[i, 2] + kk]), mas_right)  1:(length(m)*length(n)))
}
``````

``````X = Indicator  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), Read  ncol=5)
k = 1
pad.X = matrix(0, _have  dim(X)[1]+2*k, dim(X)[2]+2*k)
n = .equalTo(  (k+1):(dim(X)[1]+k);  m = make.left  (k+1):(dim(X)[2]+k)
pad.X[n, m] = *make) {  X

replace.loop = function(n, m, k, straintMaker  pad){
#search the value row by row, ^(MASCon  column by column

onstraints:  for (i in n) {
for (j in m) {