2

I have a d-dimensional function with a vector argument, and I'm trying to compute its values on a regular grid in a simple case d=2. It is natural to try outer here, which works perfectly, i.e., in the simple case

> outer(1:2, 3:4, function(x, y) x+y)
     [,1] [,2]
[1,]    4    5
[2,]    5    6

However, my function does not support natural vectorization. To illustrate, think of something like

> outer(1:2, 3:4, function(x, y) length(c(x, y)))

with a desired output (obviously, the actual result from the above code is an error)

     [,1] [,2]
[1,]    2    2
[2,]    2    2

My current workaround is something along the lines of apply(expand.grid(1:2, 3:4), 1, length), but that looks a bit clumsy to me. Is there anything as straightforward as outer for this case?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • Some [history here](http://stackoverflow.com/questions/21445605/r-outer-matrices-and-vectorizing/21446738#21446738), which links back in the comments to an earlier @agstudy post as well. – BrodieG Feb 07 '14 at 13:34

1 Answers1

6

Either you "vectorize" your function using Vectorize:

outer(1:2, 3:4, Vectorize(function(x, y) length(c(x, y))))
     [,1] [,2]
[1,]    2    2
[2,]    2    2

Or to continue the same idea using expand.grid, but with mapply:

xx = expand.grid(1:2, 3:4)
mapply(function(x, y) length(c(x, y)), xx$Var1, xx$Var2)
[1] 2 2 2 2
tonytonov
  • 25,060
  • 16
  • 82
  • 98
agstudy
  • 119,832
  • 17
  • 199
  • 261