Cheat sheet: Nested scales
Source:vignettes/articles/cheatsheet-nestedscales.Rmd
cheatsheet-nestedscales.RmdOne 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-05library(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
item data at class. eff is weighted by size, the default weight.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()
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.| 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.
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.read_scale(path, package, class)ns.read_scale(path, package, cls)
scale_catalog() lists what installed packages ship.scale_from_leaftable(leaftable, frames, leaf, weights, default_weight, name, …) pyNA: 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).
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(s, "class", "group")
[1] FALSE attr(,"offenders") [1] "GB"
scale_ancestors(s, "item", "U5")
frame member 1 sector S 2 class S1 3 group GB
scale_ancestry(x) pyU5 is under GB, which straddles both sectors, yet never under P.filter_scale(x, frame, member, …) pys["sector", "P"] is the same.p <- filter_scale(s, "sector", "P")
scale_coverage(p)
size count 0.3225806 0.6666667
example[sector:P].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
A dimension package subclasses the scale (S7) and answers a few hooks; every verb on this sheet then takes its objects.
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"
-
scale_payload_slice(),scale_payload_collapse(): per-leaf payload (a geometry) when leaves are subset, or merged byprune_scale(). -
scale_payload_parts(): rows added toscale_tree(). -
scale_write_payload(),scale_read_payload(): the payload in definition files. -
scale_leaf_pairs(): the leaf overlaps behindscale_map(). -
backend_of()and the otherbackend_*()helpers: any table backend in, the same out.
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) pyframe = settles an ambiguous one.recast_scale(data, x, source, target, rule, weight, values, …) pysource 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
size; the source frame is read from the column name.convert_scale(data, x, attribute, from_unit, to_unit, …) pyTables: data.frame, tibble, data.table, returned in kind; dtplyr and arrow are lazy and return a query unless collect = TRUE.
| 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.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).
register_scale_rule(param, rule, weight, scope) pyrule = 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, …) pyscale_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) pyrecast_scale(target = other) uses it.recast_crosswalk(data, map, source, target, rule, by, …) pyregister_scale_map(x, source, target, map) pyregister_scale_map_between(), get_scale_map(), list_scale_maps(), clear_scale_maps().join_scale(data, x, key, frame, attach, meta, labels, …) py"<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
scale_label(x, members, frame, variant) pyA 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.
- A
Calendar(timescales) and aGeoScale(geoscales) are subclasses ofNestedScale: everyscale_*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")
grid <- scale_product(space = gs,
time = cal)
recast_product(use, grid, rules = "sum",
target = list(space = "country"))
pip install "git+https://github.com/
optimal2050/nestedscales
#subdirectory=python"
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
|
- Same names, argument order, messages and
scale_id();pymarks a twin. Arguments after...are keyword-only. - R only: clusters and distances, the data link,
reconcile_scale(), the product verbs (recast_product(),filter_product(),join_product()).
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"
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.
write_scale(x, path, format, tables, …) pyf <- tempfile(fileext = ".json")
write_scale(s, f)
read_scale(f) |>
scale_id()
[1] "example@c24a3e23"
write_scale_dataset() stores data with its scales as a partitioned Arrow dataset; open_scale_dataset() gives both back.
-
Products (experimental):
scale_product()makes named scales the axes of one index;recast_product(),filter_product(),join_product(),as_scale_array(). -
Reconcile (experimental):
reconcile_scale()compares aggregates with independent totals and balances the gap. -
Data link (experimental):
bind_scale()records on a table which scale and frame its codes are on; the verbs then refuse another scale.
- A numeric
yearis a value column unlessvalues =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.