R Outer and Sweep
outer applies a function to every pair from two vectors and builds a matrix of the results. sweep adjusts a matrix by a separate value for each row or column.
Every pair multiplied
outer pairs each value from the first vector with each value from the second. The star multiplies each pair, and the result prints as a grid.
print(outer(c(1, 2), c(10, 20), "*"))An addition table
The plus sign adds each pair instead. Each row of the grid follows the first vector and each column follows the second.
print(outer(c(1, 2, 3), c(1, 2, 3), "+"))A function written for the grid
times is a function written for this grid. outer hands it one value from each vector for every cell.
times <- function(x, y) {
x * y + 1
}
print(outer(c(1, 2), c(3, 4), times))Adjust each column
sweep with margin 2 lines its values up with the columns. The first column gains 100, the second gains 200, and the third gains 300.
m <- matrix(1:6, nrow = 2)
print(m)
print(sweep(m, 2, c(100, 200, 300), "+"))Adjust each row
sweep with margin 1 lines its values up with the rows. The subtraction call then takes a separate value away from each column of the original matrix.
m <- matrix(1:6, nrow = 2)
print(sweep(m, 1, c(10, 20), "+"))
print(sweep(m, 2, c(1, 2, 3), "-"))Example
grid <- outer(c(2, 3), c(10, 20, 30), "*")
print(grid)
print(sweep(grid, 2, c(1, 2, 3), "+"))Key points
- outer takes two vectors and a function.
- The result is a matrix with one row for each value in the first vector.
- Each column of the result stands for one value in the second vector.
- sweep takes a matrix, a margin, a vector of values and a function.
- Margin 1 lines the values up with the rows and margin 2 lines them up with the columns.
- sweep returns the adjusted matrix and leaves the original matrix unchanged.
In this example, outer builds a grid of products from two row values and three column values. sweep then adds 1, 2 and 3 to the three columns of that grid.
Note
The values vector in a sweep call needs one value for each row or column on the chosen margin.
Try it Yourself
Edit the code, then press Run.
Running is simulated · rdrr.io R Snippets
Exercise
What does sweep(m, 2, c(100, 200), "+") add to the second column of m?