Mich55
Mich55

Reputation: 113

Create matrix of results from function applied to two vectors

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!

Upvotes: 1

Views: 604

Answers (3)

AnilGoyal
AnilGoyal

Reputation: 26238

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

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 102920

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"

Upvotes: 2

Sirius
Sirius

Reputation: 5429

One way:

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

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

Upvotes: 1

Related Questions