Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function with outer taking the columns of two matrices as the elements of interest

Tags:

r

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?

like image 928
kalu Avatar asked Jun 01 '11 21:06

kalu


1 Answers

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
like image 95
Prasad Chalasani Avatar answered Oct 04 '22 10:10

Prasad Chalasani