Calculate the pairwise difference of all combinations in row or column of a matrix.

pairwise_diff(X, margin = c(1, 2), na.rm = FALSE)

Arguments

X

a matrix

margin

row (1) or column (2) to apply the function

na.rm

logical. Should missing values (including NaN) be removed?

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)
pairwise_diff(X, 2)
#>      [,1] [,2] [,3]
#> [1,]    0    2    2
#> [2,]    2    0    1
#> [3,]    2    1    0