使用mapply将两个参数应用于两个矩阵的每个行应用
我有一个函数f(x,y),该函数将两个向量参数作为输入,并将向量作为输出返回(所有相等长度n)。我正在尝试将此函数应用于两个MXN矩阵M1和M2的每一行以返回MXN矩阵,即M1和M2的每一行对应于输入参数x,y。
我使用以下语法:
M3 = mapply(f, M1, M2)
给出一个错误消息,指出F将NA作为输入参数。在我的测试示例中,
M1 = rbind(c(5,0,0,6),c(20,0,0,0))
M2 = rbind(c(5,15,25,55),c(0,0,5,40))
F(M1 [1,],M2 [1,]),F(M1 [2,],M2 [,2])返回有效结果。我对Mapply的应用有什么问题?我以为这也许是第与列应用程序的问题,但是mapply(f,t(m1),t(m2))返回相同的错误,因此显然f正在喂食以外的其他行(或列(或列) M1,M2作为输入。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我们想在每一行上申请,然后按行分开矩阵,然后以
list
将其传递,请注意,
mapply
matrix (或vector
)将在每个元素上循环IE,IE是单个元素,而在data.frame/data.table/tibble
中,单个单元是列。通过按行分开(asplit
-margin = 1
),我们获得了向量的list
,此处是单位是列表元素,为@ADAM在评论中提到的是,可能需要
t
对(如果不使用f
进行测试,则不清楚)If we want to apply on each row, then split the matrix by row and pass as a
list
Note that
mapply
on amatrix
(or avector
) will loop over each element i.e. here the unit is a single element whereas indata.frame/data.table/tibble
, the single unit is a column. By splitting by row (asplit
-MARGIN = 1
), we get alist
of vectors and here the unit is a list elementAs @Adam mentioned in the comments, it may needs to be
t
ransposed (Not clear without testing withf
)