使用mapply将两个参数应用于两个矩阵的每个行应用

发布于 2025-01-23 20:39:15 字数 466 浏览 1 评论 0原文

我有一个函数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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总以为 2025-01-30 20:39:15

如果我们想在每一行上申请,然后按行分开矩阵,然后以list将其传递,

mapply(f, asplit(M1, 1), asplit(M2, 1))

请注意,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

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 transposed (Not clear without testing with f)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文