Apply a function over all combinations of arguments (output as list)

ぃ、小莉子 提交于 2020-01-01 05:47:08

问题


This solution is almost what I need, but do not worked to my case. Here is what I have tried:

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)

It works for paste example, but I get the message: Error in (function (x, y) : unused arguments (Var1 = "val1", Var2 = 2) when I try my testFunc.

My expectation is to get as result:

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

Motivation

I came from Mathematica, on which perform this operation is as simple as:

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

How can I do it in R?


回答1:


After some try and error attempts, I found a solution.

In order to make comb_apply to work, I needed to unname each exp value before use it. Here is the code:

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

Now, executing str(comb_apply(testFunc,l1,l2)) I get the desired result, without change testFunc.




回答2:


I'd use mapply or plyr::mlply for this,

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


来源:https://stackoverflow.com/questions/30686904/apply-a-function-over-all-combinations-of-arguments-output-as-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!