R outer Function


outer() function applies a function to two arrays.

outer(x, y, FUN="*", ...)
x %o% y


x,y: arrays
FUN: function to use on the outer products, default is multiply
...

>x <- c(1,2.3,2,3,4,8,12,43)
>y<- c(2,4)


Calculate logarithm value of array x elements using array y as bases:

>outer(x,y,"log")

[,1] [,2]
[1,] 0.000000 0.0000000
[2,] 1.201634 0.6008169
[3,] 1.000000 0.5000000
[4,] 1.584963 0.7924813
[5,] 2.000000 1.0000000
[6,] 3.000000 1.5000000
[7,] 3.584963 1.7924813
[8,] 5.426265 2.7131324


Add array x elements with array y elements:

> outer(x,y,"+")

[,1] [,2]
[1,] 3.0 5.0
[2,] 4.3 6.3
[3,] 4.0 6.0
[4,] 5.0 7.0
[5,] 6.0 8.0
[6,] 10.0 12.0
[7,] 14.0 16.0
[8,] 45.0 47.0


Multiply array x elements with array y elements:

> x %o% y #equal to outer(x,y,"*")

[,1] [,2]
[1,] 2.0 4.0
[2,] 4.6 9.2
[3,] 4.0 8.0
[4,] 6.0 12.0
[5,] 8.0 16.0
[6,] 16.0 32.0
[7,] 24.0 48.0
[8,] 86.0 172.0


Concatenate characters to the array elements:

>z <- c("a","b")
>outer(x,z,"paste")

[,1] [,2]
[1,] "1 a" "1 b"
[2,] "2.3 a" "2.3 b"
[3,] "2 a" "2 b"
[4,] "3 a" "3 b"
[5,] "4 a" "4 b"
[6,] "8 a" "8 b"
[7,] "12 a" "12 b"
[8,] "43 a" "43 b"