问题描述
我想知道是否有一种简单的方法来组合 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!