The following examples show what outer
is doing:
# Show the positions of the elements of the output matrix relative to the
# input vectors
A <- paste0("a", 1:3)
B <- paste0("b", 1:4)
outer(A, B, "paste", sep = " ")
#> [,1] [,2] [,3] [,4]
#> [1,] "a1 b1" "a1 b2" "a1 b3" "a1 b4"
#> [2,] "a2 b1" "a2 b2" "a2 b3" "a2 b4"
#> [3,] "a3 b1" "a3 b2" "a3 b3" "a3 b4"
# Can apply arbitrary functions of two variables (as also shown above)
C <- 1:3
D <- 1:4
outer(C, D, \(x, y) cos(x) * sin(y))
#> [,1] [,2] [,3] [,4]
#> [1,] 0.4546487 0.4912955 0.07624747 -0.4089021
#> [2,] -0.3501755 -0.3784012 -0.05872664 0.3149410
#> [3,] -0.8330500 -0.9001976 -0.13970775 0.7492288
# Dimension of outer product is sum of dimensions of inputs
# 1D (vector) and 2D (matrix) produce 3D array
E <- paste0("e", 1:3)
F <- matrix(paste0("f", 1:8), nrow = 4)
outer(E, F, "paste")
#> , , 1
#>
#> [,1] [,2] [,3] [,4]
#> [1,] "e1 f1" "e1 f2" "e1 f3" "e1 f4"
#> [2,] "e2 f1" "e2 f2" "e2 f3" "e2 f4"
#> [3,] "e3 f1" "e3 f2" "e3 f3" "e3 f4"
#>
#> , , 2
#>
#> [,1] [,2] [,3] [,4]
#> [1,] "e1 f5" "e1 f6" "e1 f7" "e1 f8"
#> [2,] "e2 f5" "e2 f6" "e2 f7" "e2 f8"
#> [3,] "e3 f5" "e3 f6" "e3 f7" "e3 f8"
Created on 2024-05-28 with reprex v2.1.0