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

Consider the 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 a certain number. I want to process the d and r columns respectively as my units of interest and apply outer to them.

The following code does this by creating lists of columns 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 clumsy and unclear. Is there a better way to achieve what I'm trying to get to?

+6
source share
1 answer

You are pretty close. As described in this related question , all you need is a Vectorize() function to convert your Fun() function to a vectorized version:

 VecFun <- Vectorize( Fun ) 

Then you can simply do:

 outer(d.cols, r.cols, VecFun ) 

eg. if you define

 Fun <- function(a,b) sum(a+b) 

and r,d defined as follows:

 J <- 5 D <- 3 R <- 4 d <- matrix( 1:(J*D), J, D) r <- matrix( 1:(J*R), J, R) 

You will get the following:

 > 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 
+10
source

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


All Articles