Consider matrices d and r with dim(d) = J x D and dim(r) = J x R.
Let fun(a, b) be a function that takes two vectors of the same length and returns some number.
I want to treat the columns of d and r respectively as my units of interest and apply outer to them.
The following code accomplishes this by creating lists of the columns of d and r and then using both outer and sapply:
d.cols <- split(d, col(d))
r.cols <- split(r, col(r))
outer(d.cols, r.cols,
function(x,y) {
sapply(seq_along(x),
function(i) {
Fun(x[[i]], y[[i]]) })} )
The code does what I want and is relatively efficient, but is clumsy and unclear. Is there a better way to accomplish what I am trying to get at?
You are pretty close. As described in this related question, all you need is the
Vectorize()function to convert yourFun()function into a vectorized version:Then you can simply do:
E.g. if you define
and
r,dmatrices are defined as follows:then you get this: