i am beginner with R and i am trying to avoid loops. This is my code

```
NII <-280
NJJ<-237
#CUTK is a nonegative matrix 282x239
ADVDOM <- array(0, dim=c(282,239))
for(i in seq(1,NII + 2){
for(j in seq(1,NJJ + 2)){
if(CUTK[i,j] > 0){
iplus <- trunc(15* CUTK[i,j] / 4)
jplus <- trunc(15* CUTK[i,j] / 4)
for(i1 in seq(i - iplus, i + iplus + 1)){
for(j1 in seq(j - jplus, j+ jplus)){
if(i1 <= NII + 1 && i1 > 1 && j1 <= NJJ + 1 && j1 > 1){
ADVDOM[i1,j1] <- 1
}
}
}
}
}
}
```

These are my attemps, but they don't work. I can't spot the mistakes.

```
#1
i <- 1 : (NII + 2)
j <- 1 : (NJJ + 2)
outer(i,j, Vectorize(function(i,j){
if(CUTK[i,j] > 0){
iplus <- trunc(15* CUTK[i,j] / 4)
jplus <- trunc(15* CUTK[i,j] / 4)
i1 <- (i - iplus) : (i + iplus + 1)
j1 <- (j - jplus) : (j + jplus)
outer(i1,j1,Vectorize(function(i1,j1){
if(i1 <= NII + 1 && i1 > 1 && j1 <= NJJ + 1 && j1 > 1){
ADVDOM[i1,j1] <- 1
}
}))
}
}))
#2
sapply(1: NII + 2 , function(i){
sapply(1: NJJ + 2, function(j){
if(CUTK[i,j] > 0){
iplus <- trunc(15* CUTK[i,j] / 4)
jplus <- trunc(15* CUTK[i,j] / 4)
sapply(i - iplus: i + iplus + 1 , function(i1){
sapply(j - jplus : j + jplus, function(j1){
if(i1 <= NII + 1 && i1 > 1 && j1 <= NJJ + 1 && j1 > 1){
ADVDOM[i1,j1] <- 1
}
})
})
}
})
})
#3
ij <- expand.grid(i=1:(NII + 2), j=1:(NJJ + 2))
invisible(apply(ij,1, function(ij){
if(CUTK[ij[1],ij[2]] > 0){
iplus <- trunc(PrognosticSubDomainFactor * CUTK[i,j] / DXK)
jplus <- trunc(PrognosticSubDomainFactor * CUTK[i,j] / DYK)
ijplus <- expand.grid(ip = (ij[1] - iplus):(ij[1] + iplus + 1), jp = (ij[2] - jplus):(ij[2] + jplus) )
apply(ijplus, 1 , function(ijplus){
if(ijplus[1] <= NII + 1 && ijplus[1] > 1 && ijplus[2] <= NJJ + 1 && ijplus[2] > 1){
ADVDOM[ijplus[1],ijplus[2]] <- 1
}
})
}
}))
```