How to combine rapply() and mapply(), or how to use mapply/Map recursively?

自闭症网瘾萝莉.ら 提交于 2019-11-30 22:04:23

Or you can write a recursive function combined with Map to achieve this, which works as long as A and B have the same structure:

s <- function(x, y) tryCatch(x + y, error = function(e) Map(s, x, y))
s(A, B)

[[1]]
[[1]][[1]]
[1] 2 4 6

[[1]][[2]]
[1] 4 6 8


[[2]]
[[2]][[1]]
[1] 8 6 4

[[2]][[2]]
[1] 6 4 2

Not sure if you can use rapply in this case, which loops through a single list recursively. But in order to loop through two lists recursively at the same time, you need a higher level of recursion? Am I wrong?

You can use Map recursively (twice) to accomplish this:

Map(function(i, j) Map(function(x, y) x + y, i, j), A, B)

[[1]]
[[1]][[1]]
[1] 2 4 6

[[1]][[2]]
[1] 4 6 8


[[2]]
[[2]][[1]]
[1] 8 6 4

[[2]][[2]]
[1] 6 4 2

To use mapply, you would need simplify=FALSE, but that is the default for Map. The outer list elements are fed to the first Map and the inner list elements are fed to the second Map.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!