---
name: statgl
description: >
  Query, inspect, retrieve, tabulate and visualize Statistics Greenland Statbank
  data from R with the statgl package. Use this skill whenever the user mentions
  statgl, statgl_search, statgl_meta, statgl_url, statgl_fetch, statgl_plot,
  statgl_table, statgl_crosstable, theme_statgl, scale_color_statgl,
  scale_fill_statgl, px_all, px_top, px_agg, or wants to retrieve official
  Greenland statistics from bank.stat.gl in R. Prefer statgl for Statistics
  Greenland-specific R workflows; use the generic PxWeb API v1 skill for raw
  HTTP/API mechanics and the Statistics Greenland Statbank profile for local
  source-link and provenance rules.
compatibility: >
  Requires an R environment with the development version of statgl from GitHub
  for execution. The instructions can still be used as guidance without R. If
  the current agent requires this skill to be installed/imported and it is not
  available, tell the user that it must be added before claiming to use it.
metadata:
  organization: Statistics Greenland
  repository: https://github.com/StatisticsGreenland/statgl
  statbank: https://bank.stat.gl/
---

# statgl — Statistics Greenland Statbank in R

`statgl` is Statistics Greenland's R package for discovering, inspecting,
retrieving and presenting data published in the Greenland Statbank.

Install the current development version from GitHub:

```r
# install.packages("remotes")
remotes::install_github("StatisticsGreenland/statgl")
library(statgl)
```

The package's core workflow is:

```text
search -> inspect metadata -> retrieve -> calculate/reshape -> present -> cite Statbank
```

For Statistics Greenland data, combine this skill with:

- Statistics Greenland Statbank profile:
  `https://stat.gl/ai/skills/statistics-greenland-statbank/SKILL.md`
- Generic PxWeb API v1 skill for raw API mechanics:
  `https://github.com/janbrus/pxwebapi-skills/tree/main/pxwebapi-v1-generic-skill`

## 1. Find the correct table — `statgl_search()`

Use free-text search when the table ID is not already known:

```r
statgl_search("population january 1")
```

Useful arguments include:

```r
statgl_search(
  query = "population",
  path = "BE",
  lang = "en"
)
```

For Statistics Greenland, `lang` must be one of `"da"`, `"en"`, or `"kl"`.
Search results contain table IDs, titles and paths. Prefer a current table that
matches the user's geography, population universe, time frequency and requested
variables. Do not choose a table solely because its title contains one keyword.

`statgl_search()` corresponds to the Statistics Greenland PxWeb API's HTTP GET
`?query=` discovery mechanism. Agents without R can use the same route directly:

```text
https://bank.stat.gl/api/v1/en/Greenland?query=population
https://bank.stat.gl/api/v1/en/Greenland/BE?query=population
```

Use API search before scraping HTML pages or guessing table identifiers. The
`?query=` request discovers candidate tables; it does not retrieve selected data
cells. After discovery, inspect metadata for the chosen table before querying it.

## 2. Inspect metadata before querying — `statgl_meta()`

Always inspect metadata when variable names or codes are not already known:

```r
m <- statgl_meta("BEESTA")
m$title
m$url
m$variables
```

`m$variables` exposes the API variable code, label, elimination flag, time flag,
value codes and value labels. Query with **value codes from metadata**, not guessed
labels.

A safe agent workflow is:

```r
m <- statgl_meta("BEESTD")
m$variables
```

then select exact codes from each variable's `values` list before calling
`statgl_fetch()`.

Never invent a code such as a locality, sex, place-of-birth or event code from
its displayed label when metadata can be inspected.

## 3. Resolve a table ID to its API URL — `statgl_url()`

`statgl_url()` accepts a table ID and returns the full PxWeb API URL:

```r
statgl_url("BEXSTD")
statgl_url("BEDSTD")
statgl_url("BEESTD")
statgl_url("BENSTD")
```

For Statistics Greenland table IDs, the third character can encode language:

- `D` -> Danish (`da`)
- `E` -> English (`en`)
- `N` -> Kalaallisut (`kl`)
- the physical API table is normally stored with `X` in that position

`statgl_url()` understands this Statistics Greenland convention and resolves the
physical API table. Do not manually rewrite an API path if `statgl_url()` can do
it safely.

## 4. Retrieve data — `statgl_fetch()`

Use either a table ID or a URL:

```r
x <- statgl_fetch("BEESTA")
```

or:

```r
x <- statgl_url("BEXSTA") |>
  statgl_fetch()
```

Pass selections using the **variable codes returned by `statgl_meta()`**:

```r
x <- statgl_fetch(
  "BEESTA",
  gender = c("M", "K"),
  age = 61:63,
  time = 2012:2026
)
```

If a variable code contains spaces, quote it:

```r
x <- statgl_fetch(
  "BEESTA",
  `place of birth` = c("N", "S"),
  gender = c("M", "K")
)
```

### Elimination behavior

Eliminable variables are eliminated by default when not explicitly selected.
This is convenient for small default queries, but it is important for agents to
understand the consequence.

Use:

```r
statgl_fetch("BEXSTA", .eliminate_rest = FALSE)
```

to return all values for remaining eliminable variables instead of automatically
reducing them to their elimination/default value.

If totals or every category are required, make the selection explicit or use
`.eliminate_rest = FALSE` deliberately. Never assume omitted dimensions mean
"all values".

### Request helpers

Use `px_all()` and `px_top()` rather than manually constructing PxWeb filters:

```r
statgl_fetch("BEXST1", time = px_all())
statgl_fetch("BEXST1", time = px_top(5))
```

`px_top(n)` requests the first `n` values, except for a time variable where it
requests the last `n` values. `px_all(pattern)` requests all matching values and
supports wildcard patterns such as `"*5"`. `px_agg()` is available for PxWeb
aggregation files when applicable.

## 5. Prefer codes when stable downstream processing matters

`statgl_fetch()` can return display labels or codes depending on the package
options used in the call/version. For reproducible filtering, joins and derived
statistics, prefer stable variable/value codes where the workflow needs them.
Inspect the installed package help for the current arguments, especially:

```r
?statgl_fetch
```

Common Statistics Greenland production code uses `.col_code` and `.val_code`
when code-preserving output is needed. Do not assume display labels are stable
identifiers across languages.

## 6. Calculate requested aggregates in R

PxWeb returns the selected cells; a user-defined age band, sum, share, rate or
other derived measure may need to be calculated after retrieval.

Example: age 61-63 summed by year, sex and place of birth:

```r
library(dplyr)

result <- statgl_fetch(
  "BEESTD",
  age = 61:63,
  locality = "9570800SIS",
  gender = c("M", "K"),
  `place of birth` = c("N", "S"),
  time = 2012:2026,
  .eliminate_rest = FALSE,
  .col_code = TRUE,
  .val_code = TRUE
) |>
  group_by(time, gender, `place of birth`) |>
  summarise(value = sum(value, na.rm = TRUE), .groups = "drop")
```

When totals are required, it is often safer to retrieve the mutually exclusive
base categories and calculate totals in R. This makes consistency checks such as
`M + K = total` and `N + S = total` possible.

## 7. Visualization

For ggplot2 output, the package exports Statistics Greenland design helpers:

```r
library(ggplot2)

ggplot(x, aes(time, value, color = gender)) +
  geom_line() +
  scale_color_statgl() +
  theme_statgl()
```

Also available: `scale_fill_statgl()`.

For interactive Highcharts output use `statgl_plot()`:

```r
statgl_plot(
  x,
  x = time,
  y = value,
  group = gender,
  title = "Population",
  ylab = "Persons"
)
```

`statgl_plot()` can infer common chart types and supports explicit types,
grouping, stacking/positioning, palettes, labels, tooltips, locale formatting,
heatmaps and downloadable data. Read `?statgl_plot` before using advanced chart
options because its interface evolves with the development package.

## 8. Tables

Use `statgl_table()` for a styled Statistics Greenland HTML table and
`statgl_crosstable()` when a cross-table layout is more appropriate.

```r
statgl_table(
  df,
  .digits = 0,
  .year_col = time,
  .replace_nas = ".."
)
```

`statgl_table()` supports mobile column hiding, row groups, captions, footnotes,
bold rows, number formatting and Statistics Greenland table styling.

## 9. Source and provenance are mandatory

The R package is a retrieval/presentation tool; the statistical source remains
Statistics Greenland's Statbank.

When numerical Statbank data are used in an answer, apply the Statistics
Greenland Statbank profile and include a clickable `bank.stat.gl` source link.
The source-link requirement must never block retrieval or presentation of the
answer.

If the result contains derived values, state that they were calculated from the
underlying Statbank cells when material to interpretation.

## 10. Fallback behavior for agents

If direct HTTP POST is unavailable but an R runtime is available, **try
`statgl::statgl_fetch()` instead of stopping after displaying a POST body**.

If R is not available, use the generic PxWeb API v1 skill to construct and
execute the query with whatever HTTP-capable tool is available.

If neither execution route exists, provide the reproducible query/code and be
explicit that the numerical result was not executed or verified. Never fabricate
values.

## Common pitfalls — avoid

- Do not scrape an HTML Statbank result page when the API or `statgl` can retrieve the data.
- Do not guess table variable codes or value codes; inspect metadata.
- Do not assume omitted eliminable dimensions mean "all".
- Do not confuse a district/municipality with a locality; choose the table and geography dimension deliberately.
- Do not filter on translated display labels when stable codes are available.
- Do not claim a skill was installed merely because its URL was discovered or read.
- Do not present unexecuted R output as if it were retrieved data.
- Do not cite GitHub or this skill as the statistical source; cite `bank.stat.gl`.

## References

- Package repository: `https://github.com/StatisticsGreenland/statgl`
- Statistics Greenland Statbank: `https://bank.stat.gl/`
- Function summary: `references/functions.md`
