如何结合使用rapply()和mapply(),或者如何递归使用mapply/Map? [英] How to combine rapply() and mapply(), or how to use mapply/Map recursively?

查看:80
本文介绍了如何结合使用rapply()和mapply(),或者如何递归使用mapply/Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种简单的方法来组合rapply( , how = "replace")mapply()的功能,以便在嵌套列表上递归使用mapply().

I was wondering if there's a simple way to combine the functions of rapply( , how = "replace") and mapply(), in order to use mapply() on nested lists recursively.

例如,我有两个嵌套列表:

For instance, I have two nested lists:

A = list(list(c(1,2,3), c(2,3,4)), list(c(4,3,2), c(3,2,1)))
B = list(list(c(1,2,3), c(2,3,4)), list(c(4,3,2), c(3,2,1)))

比方说,我想将function(x, y) x + y应用于A和B中的所有相应元素,并保留嵌套结构.预期的结果将是

Let's say I want to apply function(x, y) x + y to all the corresponding elements in A and B and preserve the nested structure. The desired result would be

result = list(list(c(2,4,6), c(4,6,8)), list(c(8,6,4), c(6,4,2)))

我认为这应该是rapply(x, f, how = "replace")mapply()类似物,但无法弄清楚如何集成它们.有人能在这方面给我一些建议吗?

I think this should be a mapply() analog of rapply(x, f, how = "replace"), but couldn't figure out how to integrate them. Could anyone kindly give me some pointers on this?

另一个快速的问题是,对于密集型计算,嵌套列表或多维数组,通常更快?任何评论都非常感谢!

Another quick question is, which is usually faster for intensive computation, nested lists or multidimensional arrays? Any comments are very much appreciated!

推荐答案

或者您可以编写与Map结合使用的递归函数来实现这一点,只要A和B具有相同的结构即可.

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

不确定在这种情况下是否可以使用rapply,它会递归遍历单个列表.但是,为了同时递归地遍历两个列表,您需要更高级别的递归吗?我错了吗?

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?

这篇关于如何结合使用rapply()和mapply(),或者如何递归使用mapply/Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆