0

If I have

x=c(2,4,8)
y=c(10,20,30)
f=sum

How do I get a matrix of function f applied to each combination of x and y elements? ie I want to get the matrix:

12, 14, 18
22, 24, 28
32, 34, 38

(Or the transpose of it)

I need something like mapply, but I need a matrix of results rather than a vector of element-wise function applications (eg mapply(sum,x,y) just gives 12, 24, 38, rather than a matix)

EDIT

Solution is: outer(x, y, '+'), but not outer(x, y, sum)

f=sum was a really bad choice on my behalf. Instead,

x=c(2,4,8)
y=c(10,20,30)
f=function(a,b) {paste0(a,b)}  #A better function example than 'sum'

outer(x, y, f) 

yields:

     [,1]  [,2]  [,3] 
[1,] "210" "220" "230"
[2,] "410" "420" "430"
[3,] "810" "820" "830"

Thanks @tmfmnk and @Roland!

Mich55
  • 93
  • 13

3 Answers3

1

outer will also work. Actually sum and + are different when vectorised operations are carried out. sum will result in aggregation of all elements of the given vector and a single element will be in output, whereas + carries out sum of corresponding elements of two vectors and output will also be a vector containing same number of elements. Therefore,

x=c(2,4,8)
y=c(10,20,30)

outer(x, y, `+`)
     [,1] [,2] [,3]
[1,]   12   22   32
[2,]   14   24   34
[3,]   18   28   38
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
1

Try Vectorize over f when you use outer

> outer(x, y, Vectorize(f))
     [,1]  [,2]  [,3]
[1,] "210" "220" "230"
[2,] "410" "420" "430"
[3,] "810" "820" "830"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

One way:

expand.grid( x,y ) %>%
    apply( 1, f ) %>%
    matrix( byrow=T, nrow=length(x) )

( .. which I see now was already in the comments)

Sirius
  • 5,224
  • 2
  • 14
  • 21