Row Sums/Means of Sparse Symmetric Matrices
rowSums.dist.RdCompute the row (column) sums or means for a sparse symmetric (distance) matrix.
Usage
rowSums.dist(x, na.rm = FALSE)
rowMeans.dist(x, na.rm = FALSE, diag = TRUE)
colSums.dist(x, na.rm = FALSE)
colMeans.dist(x, na.rm = FALSE, diag = TRUE)Details
These functions are more efficient than expanding an object of
class dist to matrix and using rowSums or rowMeans.
colSums and colMeans are provided for convenience.
However, note that due to symmetry the result is always the
same as for rowSums or rowMeans.
Examples
##
x <- matrix(runif(10*2),ncol=2)
d <- dist(x)
rowSums(as.matrix(d))
#> 1 2 3 4 5 6 7 8
#> 3.827439 5.748148 5.545453 3.478715 5.014777 4.025633 4.945647 3.222141
#> 9 10
#> 3.646035 3.906588
rowSums.dist(d) # the same
#> [1] 3.827439 5.748148 5.545453 3.478715 5.014777 4.025633 4.945647 3.222141
#> [9] 3.646035 3.906588
rowMeans(as.matrix(d))
#> 1 2 3 4 5 6 7 8
#> 0.3827439 0.5748148 0.5545453 0.3478715 0.5014777 0.4025633 0.4945647 0.3222141
#> 9 10
#> 0.3646035 0.3906588
rowMeans.dist(d) # the same
#> [1] 0.3827439 0.5748148 0.5545453 0.3478715 0.5014777 0.4025633 0.4945647
#> [8] 0.3222141 0.3646035 0.3906588
rowMeans.dist(d, diag = FALSE) # not the same
#> [1] 0.4252710 0.6386832 0.6161614 0.3865239 0.5571975 0.4472925 0.5495164
#> [8] 0.3580156 0.4051150 0.4340653
## NAs
d[3] <- NA
rowSums.dist(d, na.rm = TRUE)
#> [1] 3.418437 5.748148 5.545453 3.069713 5.014777 4.025633 4.945647 3.222141
#> [9] 3.646035 3.906588
rowMeans.dist(d, na.rm = TRUE)
#> [1] 0.3798263 0.5748148 0.5545453 0.3410792 0.5014777 0.4025633 0.4945647
#> [8] 0.3222141 0.3646035 0.3906588