Writes a new diagonal onto a square numeric matrix, leaving the off-diagonal values and the dimnames unchanged.
Details
A character replace is a summary computed over every value in the matrix,
including the current diagonal. "min", "max", "mean", and "median"
propagate NA, so a matrix containing NA yields an NA diagonal. "mode"
returns the most frequent value. "geometric" is the exponential of the mean
log of the positive, non-missing values and errors when there are none.
A numeric replace is written directly. It may be one finite value or a
finite vector as long as one side of the matrix, in which case each diagonal
position takes its own value.
Non-square input, non-numeric input, and a replace that is neither
character nor numeric are errors.
See also
precise_transform(), whose diagonal argument performs the same
operation on a collection and records it in history.
Examples
data(data_cell_cycle, package = "PreciseDist")
cells <- c(1:4, 60:63, 118:121)
cell_cycle <- as.matrix(data_cell_cycle[cells, 2:41])
rownames(cell_cycle) <- paste0(data_cell_cycle$Cell_cycle[cells], "_", cells)
euclidean <- as.matrix(stats::dist(cell_cycle))
diag(euclidean)[1:3]
#> G1_1 G1_2 G1_3
#> 0 0 0
# The default writes the median of every value in the matrix.
diag(pd_diagonal(euclidean))[1:3]
#> G1_1 G1_2 G1_3
#> 7.251484 7.251484 7.251484
# A numeric replacement is written directly.
diag(pd_diagonal(euclidean, replace = 1))[1:3]
#> G1_1 G1_2 G1_3
#> 1 1 1