繁体   English   中英

如何在R中递归Map()函数(通过嵌套列表)?

[英]How to Map() a function recursively (through nested lists) in R?

免责声明:这不是此问题的重复项: 如何将rapply()和mapply()结合使用,或者如何递归使用mapply / Map? 在这个问题之上,我在问如何将额外的函数参数合并到递归中。

所以我有清单:

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

而且我需要递归地对其应用不同的功能,以保留列表结构。 大概,当函数是mean()时,执行此操作的递归函数如下所示:

recursive = function(x, y){
  if(is.null(y)){
    if(is.atomic(x)){
      x*x
    } else{
      Map(recursive, x)
    }
  } else{
    if(is.atomic(y) && is.atomic(x)){
      x*y
    } else{
      Map(recursive, x, y)
    }
  }
}

因此,理想的结果将是:

recursive(A,B)

我想知道如何将这种递归推广到除硬编码function(x,y) x*y之外的任何函数function(x,y) x*y以便我可以方便地更改函数? 在这种情况下,它将以:

recursive = function(somefunction, x, y){
....
}

哪里

somefunction = function(x,y) x*y #or any other function taking x and y as inputs

谁能告诉我出路? 非常感谢。

您可以使用

recursive  <- function(fun, x, y) {
    if(is.atomic(x) && is.atomic(y)) {
        match.fun(fun)(x, y) 
    } else  {
        Map(recursive, x, y, MoreArgs=list(fun=fun))
    }
}

原因是Map调用mapply并且mapply具有MoreArgs=参数,您可以在其中指定要传递给不想迭代的调用函数的其他参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM