Reputation: 2682
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?
Upvotes: 8
Views: 6973
Reputation: 20282
You are pretty close. As described in this related question, all you need is the Vectorize()
function to convert your Fun()
function into a vectorized version:
VecFun <- Vectorize( Fun )
Then you can simply do:
outer(d.cols, r.cols, VecFun )
E.g. if you define
Fun <- function(a,b) sum(a+b)
and r,d
matrices are defined as follows:
J <- 5
D <- 3
R <- 4
d <- matrix( 1:(J*D), J, D)
r <- matrix( 1:(J*R), J, R)
then you get this:
> outer(d.cols, r.cols, VecFun)
1 2 3 4
1 30 55 80 105
2 55 80 105 130
3 80 105 130 155
Upvotes: 11