Merges only units the constraint allows to be merged, so the resulting groups are contiguous in order (an ordered scale) or connected in space (an adjacency graph).

cluster_contiguous(
  data,
  x,
  k,
  frame = NULL,
  key = NULL,
  value = NULL,
  distance = "euclidean",
  scale_units = FALSE,
  adjacency = "order",
  circular = FALSE,
  linkage = "average",
  new_frame = "cluster",
  labels = "c"
)

Arguments

data

Long data: unit codes, one or more identifier columns saying which observation each row is, and a value column. A unit that is not observed over the same set as the others is an error rather than a hole.

x

A NestedScale.

k

Number of clusters.

frame

Frame whose units are clustered. Defaults to the atom frame.

key, value

Columns of data; inferred when unambiguous.

distance

A name from list_scale_distances().

scale_units

Standardise each unit's profile before measuring; see scale_distance().

adjacency

How units may be merged. "order" (the default) treats the units at frame as a sequence in member order and permits only neighbours – the clusters come out as consecutive blocks. Otherwise a two-column data frame or a square logical/0-1 matrix over the units, giving the pairs that may merge.

circular

For "order": treat the sequence as a loop, so the last unit neighbours the first. Right for a yearly cycle, wrong for a trajectory.

linkage

How the distance between two clusters is measured: "average", "complete" or "single".

new_frame

Name for the frame the clusters form.

labels

How to name the clusters: a prefix (the default "c" gives c01, c02, ...), or "medoid" to name each cluster after its representative unit, which keeps the codes meaningful.

Value

As cluster_scale(): the scale with the cluster frame added, and the assignment in the "clustering" attribute.

Details

The constraint can make k unreachable: an adjacency graph with more connected components than k cannot be merged below that number, and the function stops with the count rather than returning something that quietly violates the constraint.

Examples

s <- scale_example()
d <- data.frame(
  unit = rep(scale_units(s), each = 4),
  t = rep(sprintf("t%d", 1:4), 7), v = as.numeric(seq_len(28))
)
cl <- cluster_contiguous(d, s, k = 3)
attr(cl, "clustering")
#>   unit cluster medoid
#> 1   U1     c01   TRUE
#> 2   U2     c01  FALSE
#> 3   U3     c02   TRUE
#> 4   U4     c02  FALSE
#> 5   U5     c03  FALSE
#> 6   U6     c03   TRUE
#> 7  OTH     c03  FALSE