我想对所有参数组合调用函数。
为此我尝试了 outer
:
> outer(c(0,6,7),c(100,10,1,0.1,0.01),FUN=list)
Error in outer(c(0, 6, 7), c(100, 10, 1, 0.1, 0.01), FUN = list) :
dims [product 15] do not match the length of object [2]
我可以使用嵌套 lapply
得到我想要的东西:
do.call(c,lapply(c(0,6,7),function(type)
lapply(c(100,10,1,0.1,0.01),function(cost)
list(type=type,cost=cost)))
但我想知道是否有更好的解决方案(特别是如果我有两个以上的变量,例如,除了 epsilon
和 type
之外,还有 cost
)。
最佳答案
如何仅使用 expand.grid
来获取所有组合。可推广到任意数量的向量(参数)。然后您可以使用apply
。感觉有点乱,但确实有效...
# stick your function in the apply loop
args <- expand.grid( c(0,6,7) , c(100,10,1,0.1,0.01) )
apply( args , 1 , function(x) x[1] * x[2] )
或者,data.table
的交叉连接功能 - CJ
函数(本质上与 expand.grid
执行相同的操作)可能会派上用场,而且您可以在 data.table
的 j
中计算函数...
require( data.table )
dt <- CJ( cost = c(0,6,7) , type = c(100,10,1,0.1,0.01) )
dt[ , result := cost * type ]
# cost type result
#1: 0 1e-02 0e+00
#2: 0 1e-01 0e+00
#3: 0 1e+00 0e+00
#4: 0 1e+01 0e+00
#5: 0 1e+02 0e+00
#6: 6 1e-02 6e-02
#...snip...
关于r - 如何模拟外部+列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23899122/