Search notes:

R function: outer

Create a matrix

outer takes two vectors and a function (that itself takes two arguments) and builds a matrix by calling the given function for each combination of the elements in the two vectors.
x <- 0:2; # three columns
y <- 0:4; # five rows

m <- outer (
   y,     # First dimension:  the columns (y)
   x,     # Second dimension: the rows    (x)
   function (x, y)   x+2*y
);

class(m);
#
# "matrix"
#

dim(m);
#
# 3 5

print(m);
#
#      [,1] [,2] [,3]
# [1,]    0    2    4
# [2,]    1    3    5
# [3,]    2    4    6
# [4,]    3    5    7
# [5,]    4    6    8
Github repository about-r, path: /functions/outer/create-matrix.R

Using an operator instead of a function

In place of the function, an operator can be given which makes it easy to create a matrix with simple calculations (such as multiplying):
o <- outer(c(10, 20, 30), c(2, 4, 6), "*")
print(o)
#      [,1] [,2] [,3]
# [1,]   20   40   60
# [2,]   40   80  120
# [3,]   60  120  180
Github repository about-r, path: /functions/outer/operator.R

Using outer to create a grid for plotting

x <- y <- seq(-1, 1, len=51);

grid <- outer(
        x,
        y,
        function(x, y) {
           sin(x) * exp(y)
        }
      );

filled.contour(grid, axes = FALSE, color.palette=rainbow, asp=1);
Github repository about-r, path: /functions/outer/plot-2d.R

See also

The outer function is convenient to apply a formula on x and y values to create z values and then create a 3D surface graphic (which then can be shown, for example, with persp).
Index to (some) R functions

Index