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!