The standard R expression outer(X, Y, f)
evaluates to a matrix whose (i, j)-th entry has the value f(X[i], Y[j])
.
I would like to implement the function multi.outer
, an n-dimensional generalization of outer
: multi.outer(f, X_1, ..., X_n)
, where f is some n-ary function, would produce a (length(X_1) * ... * length(X_n)) array whose (i_1,...,i_n)-th entry has the value f(X_1[i_1], ..., X_n[i_n])
for all valid index sets (i_1,...,i_n). Clearly, for each i in {1, ..., n}, all the elements of X_i
in multi.outer(f, X_1,...,X_i,..., X_n)
must be allowable i-th arguments for the function f
. For the case n=2, multi.outer
would do the same thing as outer
, although it would have a different signature (IOW, multi.outer(f, X, Y)
would be equivalent to outer(X, Y, f)
).
It is important to note that, although the arguments X_1, ..., X_n of multi.outer
are all vectors, they don't necessarily all have the same mode. E.g. X_1 and X_2 could be c(1, 2, 3)
and LETTERS[10:20]
, respectively.
Thanks!
How about this:
I think we can do this using Outer and Vectorize.
Now, sigm1(x=1:3) gives the required output
The only draw back with this code snippet is I am using the default values of a=-1:1 and b=-1:1. When I try to pass the same during function calling, it goes haywire. E.g.
I am unable to figure out why passing the arguments is making this difference in output.
This is one way: First use
Vectorize
andouter
to define a function that creates an n-dimensional matrix where each entry is a list of arguments on which the given function will be applied:Now
multi.outer
just needs to invokeapply
anddo.call
on this "args-matrix" :Let's try this with an example function: