Q:

Loop columns of matrix with nested apply

I am trying to loop over the columns of a matrix and change certain predefined sequences within the colomns, which are available in form of vectors.
Let's say I have the following matrix:
m2 <- matrix(sample(1:36),9,4)

       [,1] [,2] [,3] [,4]
[1,]   11    6    1   14
[2,]   22   16   27    3
[3,]   34   10   23   32
[4,]   21   19   31   35
[5,]   17    9    2    4
[6,]   28   18   29    5
[7,]   20   30   13   36
[8,]   26   33   24   15
[9,]    8   12   25    7

As an example my vector of sequence starts is a and my vector of sequence ends is b. Thus the first sequence to delete in all columns is a[1] to b[1], the 2nd a[2] to b[2] and so on.
My testing code is as follows:
testing <- function(x){
  apply(x,2, function(y){  
    a <- c(1,5)
    b <- c(2,8)
    mapply(function(y){
    y[a:b] <- NA; y
    },a,b)
  })
}

Expected outcome:
        [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]   NA   NA   NA   NA
[3,]   34   10   23   32
[4,]   21   19   31   35
[5,]   NA   NA   NA   NA
[6,]   NA   NA   NA   NA
[7,]   NA   NA   NA   NA
[8,]   NA   NA   NA   NA
[9,]    8   12   25    7

Actual result:
 Error in (function (y)  : unused argument (dots[[2]][[1]])

What is wrong in the above code? I know I could just set the rows to NA, but I am trying to get the above output by using nested apply functions to learn more about them.

A:

We get the sequence of corresponding elements of 'a', 'b' using Map, unlist to create a vector and assign the rows of 'm2' to NA based on that.
m2[unlist(Map(":", a, b)),] <- NA
m2
#       [,1] [,2] [,3] [,4]
# [1,]   NA   NA   NA   NA
# [2,]   NA   NA   NA   NA
# [3,]   34   10   23   32
# [4,]   21   19   31   35
# [5,]   NA   NA   NA   NA
# [6,]   NA   NA   NA   NA
# [7,]   NA   NA   NA   NA
# [8,]   NA   NA   NA   NA
# [9,]    8   12   25    7

