---
title: "Introduction to rKolada"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to rKolada}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

```{r opts, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

`rKolada` is an R package for *downloading*, *inspecting* and *processing* data from [Kolada](https://kolada.se/), a Key Performance Indicator database for Swedish municipalities and regions. This vignette provides an overview of the methods included in the `rKolada` package and the design principles of the package API. To learn more about the specifics of functions and to see a full list of the functions included, please see the [Reference section of the package homepage](https://lchansson.github.io/rKolada/reference/index.html) or run `??rKolada`. For a quick introduction to the package see the vignette [A quick start guide to rKolada](a-quickstart-rkolada.html).

> **Important:** All metadata and data labels in Kolada are in Swedish
> only. Function names and parameters are in English, but KPI titles,
> municipality names, and descriptions will be in Swedish.

The design of `rKolada` functions is inspired by the design and functionality provided by several packages in the `tidyverse` family. rKolada uses the base R pipe (`|>`) throughout. Some vignette examples use `dplyr`, `tidyr`, and `ggplot2` for data wrangling and visualisation:

```{r install, eval = FALSE}
install.packages("rKolada")
```

## Kolada, a Key Performance Indicator database for Swedish municipalities and regions

The Swedish Municipalities and Regions Database [Kolada](https://kolada.se/) is a openly accessible, comprehensive database containing over 4,000 Key Performance Indicators (KPIs) for a vast number of aspects of municipal and regional organisations, politics and economic life. The `rKolada` R package provides an interface to R users to directly download, explore, and simplify metadata and data from Kolada.

To get started with Kolada you might want to visit its homepage (Swedish-only) or read through the [Kolada API Swagger documentation](https://api.kolada.se/v3/docs) (English-only). However, you can also use the `rKolada` package to explore data without prior knowledge of the database.

```{r setup}
library("rKolada")
```

### The data model

Data in Kolada are stored along three basic _dimensions_:

- A KPI ID
- A point in time (year)
- A municipality/region ID

When downloading data, the user needs to specify search parameters for at least two of these three basic dimensions. (The Kolada API documentation also specifies a fourth basic dimension: _gender_. However, data for all genders is always automatically downloaded when available.) The parameters can be a single, atomic value or a vector of values.

Also, the Kolada database proves useful _groupings_ of municipalities and KPIs that can be used for further exploration, or to create unweighted averages.

Lastly, some KPIs are also available for _Organizational units_ (OUs) within municipalities, e.g. a school, an administrative subdivision or an elderly home.


### Downloading data

If the user already has knowledge of the IDs of the KPIs and/or municipalities they want to download, this can be done using the function `get_values()`. For instance, if you want to download all values for the KPI `N00945` ("Tillfälliga föräldrapenningdagar (VAB) som tas ut av män, andel av antal dagar (%)") for Sweden's three most populous cities; Stockholm (id `"0180"`), Gothenburg (Swedish: _Göteborg_; `"1480"`) and Malmö (`"1280"`) between the years 2000 and 2020:

```{r datapoint_mock, eval = FALSE}
n00945 <- get_values(
  kpi = "N00945",
  municipality = c("0180", "1480", "1280"),
  period = 2000:2020
)

head(n00945)
```

```{r datapoint, echo = FALSE}
n00945 <- rKolada:::n00945
tibble::tibble(head(n00945))
```

The relevant data points are stored in the `value` column of the resulting data.

In many cases, however, you will not know in advance exactly what KPIs to be looking for, or you might not know the IDs of Sweden's municipalities.

### Downloading metadata: `get` functions

Kolada has five different kinds of metadata entities Each one of these can be downloaded by using `rKolada`'s `get` functions. Each function returns a `tibble` with all available data for the specified metadata entity:

- KPIs: `get_kpi()`
- KPI groups: `get_kpi_groups()`
- Municipalities: `get_municipality()`
- Municipality groups: `get_municipality_groups()`
- Organizational Unit: : `get_ou()`

Each function returns a `tibble` with all available data for the specified metadata entity.

```{r kpi_df_mock, eval = FALSE}
# Download all KPI metadata as a tibble (kpi_df)
kpi_df <- get_kpi()

head(kpi_df, n = 10)
```

```{r kpi_df, echo = FALSE}
kpi_df <- rKolada:::kpi_df
tibble::tibble(head(kpi_df, n = 10))
```

All `get` functions are thin wrappers around the more general function `get_metadata()`. If you are familiar with the terminology used in the Kolada API for accessing metadata you might want to use this function instead.

### Exploring metadata

For each metadata type mentioned in the previous sections, `rKolada` offers several convenience functions to help exploring and narrowing down metadata tables. (If you are familiar with `dplyr` semantics, most of these functions are basically wrappers around `dplyr`/`tidyr` code.)

Since each `get` function above returns a table for the selected entity, a metadata table can be one of five different types. All metadata convenience functions are prefixed to reflect which kind of metadata table they operate on: `kpi`, `kpi_grp`, `municipality`, `municipality_grp`, and `ou`.

All metadata convenience functions have been designed with piping in mind, so their first argument is always a metadata tibble. Most of them also return a tibble of the same type.

The most important family of metadata convenience functions is the `search` family. Much like `dplyr::filter()` they can be used to search for one or several search terms in the entire table or in a subset of named columns:

```{r kpi_filter}
# Search for KPIs with the term "skola" in their description or title
kpi_filter <- kpi_df |> kpi_search("skola", column = c("description", "title"))
tibble::tibble(head(kpi_filter))
```

```{r munic_g_mock, eval = FALSE}
# Search for municipality groups containing the name "Arboga"
munic_g <- get_municipality_groups()

arboga_groups <- munic_g |> municipality_grp_search("Arboga")
arboga_groups
```

```{r munic_g, echo = FALSE}
munic_g <- rKolada:::munic_g
arboga_groups <- munic_g |> municipality_grp_search("Arboga")
arboga_groups
```

Another important family of exploration functions is the `describe` family of functions. These functions take a metadata table and print a human-readable summary of the most important facts about each row in the table (up to a limit, specified by `max_n`). By default, output is printed directly to the R console. But by specifying `format = "md"` you can make the `describe` functions create markdown-ready output which can be added directly to a R markdown file by setting the chunk option `results='asis'`. The output then looks as follows:

```{r describe_example, results='asis'}
kpi_filter |> kpi_describe(max_n = 2, format = "md", heading_level = 4)
```

### Extra functions for exploring KPI metadata

KPI metadata is considerably more complex than other types of metadata. To further assist in exploring KPI metadata the function `kpi_bind_keywords()` can be used to tag data with keywords (these are inferred from the KPI title) to classify KPIs and make them more searchable.

```{r keywords_example}
# Add keywords to a KPI table
kpis_with_keywords <- kpi_filter |> kpi_bind_keywords(n = 4)

# count keywords
kpis_with_keywords |>
  tidyr::pivot_longer(dplyr::starts_with("keyword"), values_to = "keyword") |>
  dplyr::count(keyword, sort = TRUE)
```

Some KPIs can be very similar-looking and it can sometimes be hard to discern which of the KPIs to use. To make sifting through data easier, `kpi_minimize()` can be used to remove all redundant columns from a KPI table. (In this case, "redundant" means "containing no information that helps in differentiating KPIs from one another", i.e. columns containing only one single value for all observations in the table):

```{r}
# Top 10 rows of the table
kpi_filter |> dplyr::slice(1:10)

# Top 10 rows of the table, with non-distinct data removed
kpi_filter |> dplyr::slice(1:10) |> kpi_minimize()
```

Note that `kpi_minimize()` operates on the _current table_. This means that results may vary depending on the data you're operating on.

### Metadata groups

Kolada provides pre-defined _groups_ of KPIs and municipalities/regions. Exploring an using thse groups can facilitate meaningful comparisons between different entities or help paint a broader picture of developments in a certain field or area.

To `get`, `search` or `describe` group metadata, use the same techniques as described above for regular metadata (relevant prefixes are `kpi_grp_` and `municipality_grp_`).

A crucial difference between group metadata and other metadata tables, however, is that group metadata comes in the form of a [nested](https://tidyr.tidyverse.org/articles/nest.html) table. Typically you might want to _unnest_ the groups in a group metadata table once yo hae found the relevant group(s) for your query. To do this, use the `unnest` functions to create a table containing unnested entities. For example, running `kpi_grp_unnest(kpi_grp_df)` using a KPI group metadata table as argument creates a `kpi_df` that can be further processed using the `kpi_` functions described in previous sections of this vignette.

In other words: a group table has one row per *group*, with members
nested inside. `unnest` expands it so you get one row per *member*,
which you can then pipe into `kpi_search()`, `kpi_describe()`, etc.


## Downloading data using metadata

An alternative approach to downloading data using known IDs is to use metadata tables to construct arguments to `get_values()`. `rKolada` provides a `*_extract_ids()` family of functions for passing a metadata table as an argument to `get_values()`. A typical workflow would be to download metadata for (groups of) KPIs and/or municipalities, use functions like `kpi_search()` to filter down the tables to a few rows, and then call `get_values()` to fetch data.

As an example, let's say we want to download all KPIs describing Gross Regional Product for all municipalities that are socioeconomically similar to Arboga, a small municipality in central Sweden:

```{r, echo = FALSE}
kpi_filter <- rKolada:::kpi_filter
munic_grp_filter <- rKolada:::munic_grp_filter
arboga <- rKolada:::arboga
grp_data <- rKolada:::grp_data
```


```{r, eval = FALSE}
# Get KPIs describing Gross Regional Product of municipalities
kpi_filter <- get_kpi() |> 
  kpi_search("bruttoregionprodukt") |>
  kpi_search("K", column = "municipality_type")
# Creates a table with two rows

# Get a suitable group of municipalities
munic_grp_filter <- get_municipality_groups() |> 
  municipality_grp_search("Liknande kommuner socioekonomi, Arboga")
# Creates a table with one group of 7 municipalities

# Also include Arboga itself
arboga <- get_municipality() |> municipality_search("Arboga")

# Get data
grp_data <- get_values(
  kpi = kpi_extract_ids(kpi_filter),
  municipality = c(
    municipality_grp_extract_ids(munic_grp_filter),
    municipality_extract_ids(arboga)
  )
)
```

To explore results we can plot the resulting data using ggplot2 and add legends to keep track of what data we are visualizing:

```{r}
# Visualize results
library("ggplot2")
ggplot(grp_data, aes(year, value, color = municipality)) +
  # One line per municipality; linetype adds distinction in B/W print
  geom_line(aes(linetype = municipality)) +
  # Separate panel per KPI; free y-scales since units differ
  facet_grid(kpi ~ ., scales = "free") +
  labs(
    title = "Gross Regional Product per capita 2012-2018",
    subtitle = "Swedish municipalities similar to Arboga",
    caption = values_legend(grp_data, kpi_filter)  # Auto-generated legend
  ) +
  # Colour-blind-friendly palette
  scale_color_viridis_d(option = "B") +
  scale_y_continuous(labels = scales::comma)
```

> **More on ggplot2?** See <https://ggplot2-book.org/>.

## Related packages

If you work with data from PX-Web APIs (Statistics Sweden, Statistics
Norway, Statistics Finland, etc.), see
[pixieweb](https://lchansson.github.io/pixieweb/) — a sibling package
that follows the same design principles as rKolada.
