如何在R中递归Map()函数(通过嵌套列表)? [英] How to Map() a function recursively (through nested lists) in R?

查看:84
本文介绍了如何在R中递归Map()函数(通过嵌套列表)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Disclaimer: this is not a duplicate of this question: How to combine rapply() and mapply(), or how to use mapply/Map recursively? On top of that question, I am asking how to incorporate extra arguments of functions into the recursion.

所以我有列表:

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()时,执行此操作的递归函数将如下所示:

And I need to apply different functions to it recursively that preserves the list structure. Presumably, a recursive function that does this goes like this, when the function is 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)
    }
  }
}

因此,期望的结果将是:

So the desired result would be:

recursive(A,B)

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

I was wondering how could I generalize this recursion to any functions beyond just the hard-coded function(x,y) x*y here so that I could change functions conveniently? In that case, it would start with:

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

其中

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

有人可以给我一个出路吗?非常感谢.

Could anyone kindly show me a way out? Thank you so much.

推荐答案

您可以使用

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=参数,您可以在其中指定要传递给不想迭代的调用函数的其他参数.

The reason is that Map calls mapply and mapply has a MoreArgs= parameter where you can specify other parameters you want to pass to the calling function that you do not want to iterate over.

这篇关于如何在R中递归Map()函数(通过嵌套列表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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