Skip to contents

Compute 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)

Arguments

x

an object of class dist.

na.rm

logical, should missing values (including NaN) be omitted from the summation?

diag

logical, should the diagonal elements be included in the computation?

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.

Value

A numeric vector of row sums.

Author

Christian Buchta

See also

as.matrix, as.dist, and rowSums.

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