0

Here is a toy example of where I'm trying to use outer but it is not working.

A=matrix(1:4,2,2) B=matrix(1:8,2,4) g=function(i,j) as.vector(t(A[i,]-B[i,c(j,2+j)])%*%(A[i,]-B[i,c(j,2+j)])) g(1,2) [1] 20 g(1,1) [1] 4 g(2,1) [1] 4 g(2,2) [1] 20 outer(1:2,1:2,g) Error in A[i, ] - B[i, c(j, 2 + j)] : non-conformable arrays 

In my actual data both A and B have really large dimensions so using for loop or mapply is very slow. Is there any way to use outer to obtain the result ?

6
  • 2
    The first line of the Details section of ?outer states: "X and Y must be suitable arguments for FUN.". Run g(1:2,1:2). Commented Jun 24, 2015 at 19:35
  • g(1:2,1:2) gives the same error Commented Jun 24, 2015 at 20:09
  • .........exactly! If your function g doesn't work with those inputs, it will never work with outer. Commented Jun 24, 2015 at 20:10
  • 1
    outer is just going to call g(c(1,1,2,2),c(1,2,1,2)). Your function isn't vectorized in a manner that handles that. Commented Jun 24, 2015 at 20:13
  • Thanks Joran that helps ... I'll try to modify it ... Commented Jun 24, 2015 at 20:17

1 Answer 1

2

You can write a helper function to deliver the values from an mapply implementation using expand.grid's capacity for enumeration all teh n x m combinations:

> gh=function(df) mapply( g, df[,1], df[,2]) > gh(expand.grid(1:2,1:2)) [1] 4 4 20 20 

The ordering will be all rows in first column, then all rows in second column, then ....

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.