I have a function f(x,y) that takes two vector arguments as input and returns a vector as output (all of equal length n). I am trying to apply this function to every row of two m x n matrices M1 and M2 to return an m x n matrix, i.e. so that every row of M1 and of M2 correspond to input arguments x,y.
I used the following syntax:
M3 = mapply(f, M1, M2)
Which gives an error message stating that f is taking NA as input arguments. In my test example,
M1 = rbind(c(5,0,0,6),c(20,0,0,0))
M2 = rbind(c(5,15,25,55),c(0,0,5,40))
and f(M1[1,],M2[1,]), f(M1[2,],M2[,2]) return valid results. What is the problem with my application of mapply? I thought that perhaps it was an issue of row vs. column applications, but mapply(f, t(M1), t(M2)) returns the same error, so obviously f is being fed something other than the respective rows (or columns) of M1,M2 as input.
CodePudding user response:
If we want to apply on each row, then split the matrix by row and pass as a list
mapply(f, asplit(M1, 1), asplit(M2, 1))
Note that mapply
on a matrix
(or a vector
) will loop over each element i.e. here the unit is a single element whereas in data.frame/data.table/tibble
, the single unit is a column. By splitting by row (asplit
- MARGIN = 1
), we get a list
of vectors and here the unit is a list element
As @Adam mentioned in the comments, it may needs to be t
ransposed (Not clear without testing with f
)