Skip to contents

One dimension at several resolutions -- frames, members, leaves -- and data moved between them by explicit rules; the engine under timescales (calendars) and geoscales (regions)

PDF, A4, 2 pages · nestedscales 0.3.0.9000 (dev) · 2026-12-05
The round trip
library(nestedscales)
s <- scale_example()
x <- data.frame(
  item = c("U1", "U2", "U3",
           "U4", "U5", "U6"),
  cap = c(1, 2, 3, 4, 5, 6),
  eff = c(.3, .4, .5, .6, .7, .8))
recast_scale(x, s, source = "item",
  target = "class",
  rule = c(cap = "sum",
           eff = "weighted_mean"))
  class cap       eff
1    G1   3 0.3666667
2    G2   7 0.5571429
3    S1  11 0.7545455
A ready-made scale, a table keyed by its leaves, one call, one rule per value column: item data at class. eff is weighted by size, the default weight.
Drawn
tree <- scale_tree(s)
tree$note <- ""
tree
<NestedScale> example@c24a3e23
├─ leaftable   data.frame [7 x 6]
│  ├─ item     leaf column          fixed
│  ├─ sector   frame                fixed
│  ├─ class    frame                fixed
│  ├─ group    frame                fixed
│  ├─ size     weight               mutable
│  └─ count    weight               mutable
├─ frames      chr [4]              fixed
├─ members     list [4]             derived
├─ leaf        chr [1]              fixed
├─ meta        list [4]             mutable
├─ attributes  data.frame [0 x 10]  mutable  attach_attributes_scale()
├─ aliases     data.frame [0 x 4]   mutable  attach_aliases_scale()
└─ labels      data.frame [0 x 4]   mutable  attach_labels_scale()
The parts of a scale: fixed ones enter its identity, derived ones follow from them, mutable ones can change. str(s) prints the tree with its notes; print(s) the frames alone. The pictures are drawn by the dimension packages -- see Plot.
Words
here timescales geoscales
frame timeframe geoframe one resolution
member timeslice region one code of a frame
leaf leaf timeslice geoleaf a member of the finest frame: one row of the leaftable
weight weight weight a numeric leaf column sizing the leaf (hours, area)
share share share a member's part of a total weight
coverage coverage coverage the part of the full scale a subset keeps

A scale is a definition, not a container: data stays in ordinary tables and is matched by its codes. Every recast routes through the leaves, so frames need not nest.

Get a ready-made scale
scale_example() py
Four frames, with the traps built in.
scale_leaftable(s)
  sector class group item size count
1      P    G1    G1   U1  100    10
2      P    G1    G1   U2  200    90
3      P    G2    GB   U3  300    30
4      P    G2    GB   U4  400    70
5      S    S1    GB   U5  500    50
6      S    S1    GC   U6  600    50
7   <NA>  <NA>  <NA>  OTH 1000     0
G1 is a class and a group; GB holds items of two classes (cross-cutting); OTH has no code above item; two weights, size the default.
scale_example2() py
A second dimension, era > period, for products.
read_scale(path, package, class)
pyns.read_scale(path, package, cls)
A definition file, a bundle or a catalogue id; scale_catalog() lists what installed packages ship.
Build from a table
scale_from_leaftable(leaftable, frames, leaf, weights, default_weight, name, …) py
One row per leaf, one column per frame, coarsest first; numeric columns become weights; NA: no code at that frame.
cities <- data.frame(
  country = c("N", "N", "N", "S", "S"),
  region = c("A", "A", "B", "C", "C"),
  city = c("a", "b", "c", "d", "e"),
  people = c(3, 2, 5, 6, 1))
places <- scale_from_leaftable(cities,
  frames = c("country", "region", "city"),
  name = "places")
scale_id(places)
[1] "places@4f21313b"
places prints its frames as a tree, summary(places) how they nest.

Then attach_labels_scale() (names to show), attach_aliases_scale() (spellings to recognise), attach_attributes_scale() (a value per member, never a weight).

Inspect
scale_frames(x, finest) py
Frame names, coarsest first; finest = TRUE the leaf frame.
scale_members(x, frame) py
Codes at a frame, in canonical order; default the leaves.

Also scale_rank(), scale_weights(), scale_leaftable(), scale_leaf_column().

scale_id(x) py
"example@c24a3e23": name and a hash of leaf column, frames and memberships; weights and labels do not enter.

summary(s): members, unassigned leaves, weight totals, how adjacent frames nest.

scale_nests(x, parent, child) py
Does every child code lie in one parent?
scale_nests(s, "class", "group")
[1] FALSE
attr(,"offenders")
[1] "GB"
A verdict with its evidence attached. Nesting is never required.
scale_crosses(x, a, b) py
Do the frames form a product (months × hours)?
scale_is_uniform(x, frame, weight, tolerance) py
Same leaf count, or weight total, in every member?
Navigate
scale_children(x, frame, member, target) py
Codes one frame down, or at target; scale_parents() up.
scale_descendants(x, frame, member, target) py
Every finer frame as frame, member; scale_ancestors() coarser.
scale_ancestors(s, "item", "U5")
   frame member
1 sector      S
2  class     S1
3  group     GB
scale_family(x, parent, child) py
Parent-child pairs of adjacent frames.
scale_ancestry(x) py
Pairs over all frames, through the leaves: U5 is under GB, which straddles both sectors, yet never under P.
Subset and coarsen
filter_scale(x, frame, member, …) py
Keep the leaves under some members; s["sector", "P"] is the same.
scale_coverage(x, weight) py
The kept share of each weight of the full scale.
p <- filter_scale(s, "sector", "P")
scale_coverage(p)
     size     count 
0.3225806 0.6666667 
A subset is a sample, named example[sector:P].
prune_scale(x, frame) py
Collapse to a coarser leaf frame, weights summed.
scale_share(x, frame, weight, within) py
Normalised weights, overall or within a parent frame.
scale_share(s, "class",
            within = "sector")
  class sector size share
1    G1      P  300   0.3
2    G2      P  700   0.7
3    S1      S 1100   1.0
scale_residuals(x, frame) py
Members that aggregate up but never receive a split ("n.e.c.").
Build a dimension package

A dimension package subclasses the scale (S7) and answers a few hooks; every verb on this sheet then takes its objects.

scale_class() py
The parent class; scale_is() is true for every subclass.
scale_vocab(x, ...) py
The words of the dimension, used in every engine message.
register_scale_class(class)
pyns.register_scale_class(cls)
In .onLoad(): read_scale() then returns the subclass; list_scale_classes().
A subclass and its hooks
lv <- scale_alias_property("frames")
Shelf <- S7::new_class("Shelf",
  parent = scale_class(),
  properties = list(levels = lv))
S7::method(scale_vocab, Shelf) <-
  function(x, ...) {
    list(object = "Shelf",
      frame = "level", frames = "levels",
      member = "bin", members = "bins",
      leaves = "bins")
  }
register_scale_class(Shelf)
sh <- S7::convert(s, Shelf)
scale_is(sh)
[1] TRUE
sh@levels
[1] "sector" "class"  "group"  "item"  
scale_alias_property() names an inherited property in the words of the dimension. A subset of sh stays a Shelf.
tryCatch(scale_members(sh, "row"),
         error = conditionMessage)
[1] "`level` = \"row\" is not a level of this Shelf; one of: sector, class, group, item"
Engine messages speak the vocabulary of the subclass.
Data onto the scale

Data is an ordinary table: one column of member codes named as its frame, numeric value columns, and identifiers (a year, a technology) kept as groups.

scale_match(x, labels, frame, source) py
Labels of a source to member codes: name, then alias, exact and case-insensitive, no fuzzy stage; frame = settles an ambiguous one.
recast_scale(data, x, source, target, rule, weight, values, …) py
Data keyed at source to target, up or down, one rule per value column.
y <- data.frame(sector = c("P", "S"),
                cap = c(10, 20))
recast_scale(y, s, target = "class",
  rule = "sum", weight = "size")
  class cap
1    G1   3
2    G2   7
3    S1  20
Down: each sector split by size; the source frame is read from the column name.
convert_scale(data, x, attribute, from_unit, to_unit, …) py
Row-wise unit conversion by a member attribute (tonnes to GJ), inherited from the nearest ancestor.

Tables: data.frame, tibble, data.table, returned in kind; dtplyr and arrow are lazy and return a query unless collect = TRUE.

Recast
rule going up (fine → coarse) going down (coarse → fine)
sum sum split by weight
weighted_mean weighted mean copy
mean mean over leaves copy
copy the common value copy
sd sd over leaves --
share, logshare value / parent total --

SCALE_RULES lists them. copy errors when values differ. A share stays keyed at source and does not mix with other rules.

values default every numeric non-key column
weight per column; else registered, else the default weight
na_action leaves without a code: "drop" (warned), "error", "keep" (an NA row)
missing_sources "na": a target with absent sources is NA; "ignore" sums what is there
parent the frame shares are taken within
recast_scale(x[1:3, 1:2], s,
  target = "sector", rule = "sum")
  sector cap
1      P  NA
2      S  NA
U4-U6 absent: both sectors NA, with a warning.
recast(x, scale, ...) py
The pipeline verb: data first, dispatching on the scale.

The two halves: recast_to_leaves() (one row per leaf, with its weight) and recast_from_leaves() (leaf-keyed data up to a frame of any scale sharing the leaf codes).

Rules and crosswalks
register_scale_rule(param, rule, weight, scope) py
The rule of a named value column, so rule = can go; scope = "calendar" for one dimension.
register_scale_rule("cap", "sum")
register_scale_rule("eff",
  "weighted_mean", weight = "count")
x |>
  recast(s, target = "sector")
  sector cap  eff
1      P  10 0.48
2      S  11 0.75

get_scale_rule(), list_scale_rules(), clear_scale_rules(). A column with no rule is an error, never a guess.

scale_map(x, source, target, weight, by, …) py
The crosswalk of two frames: leaves and weight of each overlap.
scale_map(s, "class", "group")
  class group n_from n_overlap   w w_from
1    G1    G1      2         2 300    300
2    G2    GB      2         2 700    700
3    S1    GB      2         1 500   1100
4    S1    GC      2         1 600   1100
sum splits a source by w / w_from; weighted_mean weighs by w.
scale_map_between(source, target, weight) py
The crosswalk of two named scales, by shared leaf codes; recast_scale(target = other) uses it.
recast_crosswalk(data, map, source, target, rule, by, …) py
The engine on a crosswalk built elsewhere.
register_scale_map(x, source, target, map) py
An audited crosswalk in place of the derived one; also register_scale_map_between(), get_scale_map(), list_scale_maps(), clear_scale_maps().
Join to data
join_scale(data, x, key, frame, attach, meta, labels, …) py
Add the codes of coarser frames ("<name>.<frame>"), share and weight (meta), display names (labels).
k <- data.frame(class = c("G1", "S1"),
                v = 1:2)
join_scale(k, s, attach = TRUE)
  class v example.sector example
1    G1 1              P      G1
2    S1 2              S      S1
join_scale(k, s, meta = TRUE)[1:4]
  class v example.weight example.share
1    G1 1            300     0.1428571
2    S1 2           1100     0.5238095
Codes come as factors; an existing column is never overwritten.
scale_label(x, members, frame, variant) py
Display names of codes; a code without a label comes back as itself.
Plot

A bare scale has no picture: the plots live in the dimension packages -- gg_calendar() in timescales, gg_geoscale() in geoscales. Here print(), str() and summary() describe a scale in text.

Dimension packages
  • A Calendar (timescales) and a GeoScale (geoscales) are subclasses of NestedScale: every scale_* verb here takes them, and errors speak their words.
  • Each dimension recasts in turn; the other dimension's key rides along as an identifier.
library(timescales)
library(geoscales)
cal <- calendar("m12")
gs <- geoscale_example()
scale_frames(gs)
use <- expand.grid(
  cell = scale_members(gs),
  timeslice = scale_members(cal),
  stringsAsFactors = FALSE)
use$tj <- 1
use |>
  recast(gs, target = "country",
         rule = "sum") |>
  recast(cal, target = calendar("q4"),
         year = 2024, rule = "sum")
Cells to countries, then months to quarters.
grid <- scale_product(space = gs,
                      time = cal)
recast_product(use, grid, rules = "sum",
  target = list(space = "country"))
The same through a product of scales (experimental): one pass per named axis.
Python
pip install "git+https://github.com/
  optimal2050/nestedscales
  #subdirectory=python"
One line, no breaks.
import pyarrow as pa
import nestedscales as ns
s = ns.scale_example()
d = pa.table({"item": ["U1", "U2"],
              "cap": [1.0, 2.0]})
ns.recast_scale(d, s, source="item",
  target="sector", rule={"cap": "sum"})
ns.scale_id(s)  # "example@c24a3e23"
R Python
s@frames s.frames
c(cap = "sum") {"cap": "sum"}
NULL, TRUE None, True
read_scale(class = ) read_scale(cls=)
summary(s) ns.scale_summary(s)
a data frame pyarrow.Table; pandas, polars or a dict in, the same out
an S7 method on a hook hook.register(Class), from nestedscales.extend
Clusters as a new frame
cluster_scale(data, x, k, frame, method, distance, labels, …)
"pam", "hclust", "kmeans" on member profiles; a new frame right above frame.
prof <- data.frame(
  item = rep(scale_members(s), each = 4),
  t = rep(paste0("t", 1:4), 7),
  v = 1:28)
cl <- cluster_scale(prof, s, k = 3,
                    labels = "medoid")
scale_members(cl, "cluster")
[1] "U2"  "U4"  "OTH"
Named by representative; assignment in attr(cl, "clustering").

cluster_contiguous() merges only neighbours; cluster_sweep() scores a range of k; cluster_medoids() gives the representatives; scale_distance() and SCALE_DISTANCES the distances.

Definition files and more
write_scale(x, path, format, tables, …) py
JSON or YAML, tables inline or in a bundle (Arrow, CSV); the same file reads in R and Python.
f <- tempfile(fileext = ".json")
write_scale(s, f)
read_scale(f) |>
  scale_id()
[1] "example@c24a3e23"
The identity survives the file.

write_scale_dataset() stores data with its scales as a partitioned Arrow dataset; open_scale_dataset() gives both back.

Pitfalls
  • A numeric year is a value column unless values = names the real ones: it gets summed.
  • A code may repeat across frames (G1): name the frame, never rely on the code alone.
  • missing_sources = "ignore" turns incomplete data into a plausible number.
  • Leaves without a code at the target are dropped with a warning: na_action = "keep" conserves the total.
  • Numeric leaftable columns become weights: per-member values go in attributes =.
  • prune_scale() to a frame needs the frames above it to nest.