Skip to contents

balancedClusters() takes as input a set of coordinates (two or more columns) and returns a vector indicating cluster membership such that clusters are as compact as possible while also having nearly the same number of members.

Usage

balancedClusters(x, k, maxIter = 100, ...)

rebalanceClusters(dists, clusters, maxIter = 100)

Arguments

x

A data.frame or matrix with at least two columns representing coordinates.

k

Numeric or integer: Number of clusters to create.

maxIter

Numeric or integer: Maximum number of tries for re-balancing.

...

Arguments to pass to stats::hclust().

dists

A square distance matrix representing distances between coordinates.

clusters

A vector with group memberships, one value per set of coordinates in x or row/column in x.

Value

Both functions return a vector of cluster assignments, one value per coordinate set.

Details

rebalanceClusters() takes as input a distance matrix representing distances between coordinates and a vector indicating group memberships and re-assigns members to different clusters so they are still as compact as possible while ensure the number of members in each group are as equal as possible.

Functions

  • rebalanceClusters(): Re-assign clusters so they are of equal size

Examples


coords <- data.frame(
  x = c(rnorm(60), rnorm(140, 5)),
  y = c(rnorm(120), rnorm(80, -3))
)

# balanced clusters
groups2 <- balancedClusters(coords, k = 2)
groups4 <- balancedClusters(coords, k = 4)

oldpar <- par()
par(mfrow = c(1, 2))

plot(coords, col = groups2, pch = groups2, main = '2 groups')
plot(coords, col = groups4, pch = groups4, main = '4 groups')


par(oldpar)
#> Warning: graphical parameter "cin" cannot be set
#> Warning: graphical parameter "cra" cannot be set
#> Warning: graphical parameter "csi" cannot be set
#> Warning: graphical parameter "cxy" cannot be set
#> Warning: graphical parameter "din" cannot be set
#> Warning: graphical parameter "page" cannot be set

# rebalance clusters
dists <- dist(coords) 
clusts <- hclust(dists)
prelim_clusts <- cutree(clusts, k = 3)
balanced_clusts <- rebalanceClusters(dists, clusters = prelim_clusts)

oldpar <- par()
par(mfrow = c(1, 2))

plot(coords, col = prelim_clusts, pch = prelim_clusts, main = 'Imbalanced')
plot(coords, col = balanced_clusts, pch = balanced_clusts,
  main = 'Balanced')


par(oldpar)
#> Warning: graphical parameter "cin" cannot be set
#> Warning: graphical parameter "cra" cannot be set
#> Warning: graphical parameter "csi" cannot be set
#> Warning: graphical parameter "cxy" cannot be set
#> Warning: graphical parameter "din" cannot be set
#> Warning: graphical parameter "page" cannot be set