【问题标题】:Apply a function over all combinations of arguments (output as list)对所有参数组合应用函数(输出为列表)
【发布时间】:2015-06-06 19:47:57
【问题描述】:

This solution 几乎是我需要的,但不适用于我的情况。 这是我尝试过的:

comb_apply <- function(f,...){
  exp <- expand.grid(...,stringsAsFactors = FALSE)
  apply(exp,1,function(x) do.call(f,x))
}

#--- Testing Code
l1 <- list("val1","val2")
l2 <- list(2,3)

testFunc<-function(x,y){
  list(x,y)
}

#--- Executing Test Code
comb_apply(testFunc,l1,l2)
comb_apply(paste,l1,l2)

它适用于 paste 示例,但当我尝试使用 testFunc 时,我收到消息:Error in (function (x, y) : unused arguments (Var1 = "val1", Var2 = 2)

我的期望是得到结果:

list(list("val1",2),list("val1",3),list("val2",2),list("val2",3))

动机

我来自Mathematica,在其上执行这个操作很简单:

l1 = {"val1", "val2"}
l2 = {2, 3}
testFunc = {#1, #2} &
Outer[testFunc, l1, l2]

R怎么办?

【问题讨论】:

  • R 有一个?outer 函数。
  • @sgibb 我需要一个通用案例,其中可能有 2 个以上的列表。

标签: r apply


【解决方案1】:

经过多次尝试和错误尝试,我找到了解决方案。

为了使comb_apply 工作,我需要在使用前unname 每个exp 值。代码如下:

comb_apply <- function(f,...){
  exp <- expand.grid(...,stringsAsFactors = FALSE)
  apply(exp,1,function(x) do.call(f,unname(x)))
}

现在,执行str(comb_apply(testFunc,l1,l2)) 我得到了想要的结果,没有改变testFunc

【讨论】:

    【解决方案2】:

    我会为此使用mapplyplyr::mlply

    comb_apply <- function(f,..., MoreArgs=list()){
      exp <- unname(expand.grid(...,stringsAsFactors = FALSE))
      do.call(mapply, c(list(FUN=f, SIMPLIFY=FALSE, MoreArgs=MoreArgs), exp))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2016-05-02
      • 2021-01-14
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多