How to emulate an external + list?

I want to call a function for all combinations of arguments. For this, I tried 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]

I can get what I want using nested 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)))

but I wonder if there is a better solution (especially if I have more than two variables, say, epsilonin addition to typeand cost).

+4
source share
3 answers

How easy to use expand.gridto get all the combinations. Summarize any number of vectors (arguments). Then you can use apply. Feels a little messy, but does the job ...

# 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) , , j of data.table...

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...
+3

data.table CJ - :

CJ(type = c(0, 6, 7), cost = c(100, 10, 1, 0.1, 0.01))

    type  cost
 1:    0 2e-02
 2:    0 1e-01
 3:    0 1e+00
 4:    0 1e+01
 5:    0 1e+02
 6:    6 2e-02
 7:    6 1e-01
 8:    6 1e+00
 9:    6 1e+01
10:    6 1e+02
11:    7 2e-02
12:    7 1e-01
13:    7 1e+00
14:    7 1e+01
15:    7 1e+02

, apply(dt, 1, as.list)

0

You can use expand.gridand mapply:

tmp = expand.grid(c(0,6,7),c(100,10,1,0.1,0.01))
do.call(".mapply",   ##".mapply" seems handier for this since you don't have to specify each `...` argument
        c(function(x, y) list(type = x, cost = y), 
          list(unname(tmp)), 
          list(NULL)))
0
source

Source: https://habr.com/ru/post/1542244/


All Articles