Apply a function to pairwise of all combinations in row or column of a matrix.
pairwise(X, margin = c(1, 2), FUN, ...)
Arguments
- X
a matrix
- margin
row (1) or column (2) to apply the function
- FUN
the function to be applied, which has two arguments
and only returns a single value.
- ...
optional arguments to FUN
Value
a matrix with the same number of row (margin = 1) or column (margin = 2)
with the original matrix.
Examples
X <- matrix(c(1, 2, 3, 4,
1, 2, 5, 6,
1, 2, 5, 7), nrow = 4)
FUN <- function(x, y, na.rm = FALSE) {
sum(x != y, na.rm = na.rm)
}
pairwise(X, 2, FUN, na.rm = TRUE)
#> [,1] [,2] [,3]
#> [1,] 0 2 2
#> [2,] 2 0 1
#> [3,] 2 1 0