
Combining with external data: school locations (DUO)
Source:vignettes/articles/duo-schools.Rmd
duo-schools.RmdPDOK is rarely the only source you need. A common pattern is to take
a table from another open API, turn it into spatial data, and combine it
with authoritative PDOK geometry. This article does that with DUO’s open data on schools. It shows that
combining sources often means a little data wrangling first, and that an
external table with BAG ids pairs naturally with a server-side
filter on the BAG.
library(pdokr)
library(tmap)
#> Registered S3 method overwritten by 'stars':
#> method from
#> st_interpolate_aw.stars sf
library(sf)
#> Linking to GEOS 3.14.1, GDAL 3.12.2, PROJ 9.7.1; sf_use_s2() is TRUE
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(httr2)DUO publishes its data through a CKAN open-data API. Every table
is one resource. Some are large, so this helper fetches one in pages,
letting httr2 retry a request that drops or that the DUO
server answers with a temporary gateway error.
read_duo <- function(resource_id, page_size = 5000) {
pages <- list()
offset <- 0
repeat {
resp <- request("https://onderwijsdata.duo.nl/api/3/action/datastore_search") |>
req_url_query(resource_id = resource_id, limit = page_size, offset = offset) |>
req_retry(
max_tries = 6, backoff = ~ 5,
is_transient = ~ resp_status(.x) %in% c(429, 502, 503, 504)
) |>
req_perform() |>
resp_body_json(simplifyVector = TRUE)
page <- resp$result$records
if (length(page) == 0) break
pages[[length(pages) + 1]] <- page
if (nrow(page) < page_size) break
offset <- offset + page_size
}
do.call(rbind, pages)
}Fetch the education locations
The onderwijslocaties resource lists every location
where education may take place, each with coordinates and a
BAG_ID: the identifier of the BAG verblijfsobject
(unit of use) the location occupies.
locations <- read_duo("a7e3f323-6e46-4dca-a834-369d9d520aa8")
nrow(locations)
#> [1] 13670There is a catch: these are possible education locations, not recognized schools. A conference center that hosts the odd exam, or a commercial training firm, is in here too. Mapping them straight away would put dots where no school exists.
Keep only the recognized schools
To find the schools recognized in law we combine two more DUO tables.
The relaties... resource links a location
(ONDERWIJSLOCATIECODE) to a recognized institution
(VESTIGINGSCODE); the vestigingserkenningen
resource describes that institution — its name and the education law it
falls under (WET). Both tables are historical, so a row
counts only when it has no EINDDATUM.
relations <- read_duo("c18ec7dd-aa4e-4b51-997c-782955f1aa38")
institutions <- read_duo("01fd2a5f-40af-456f-864d-13265a51e5e2")
# translate the education-law code into a readable sector
sectors <- c(WPO = "Primary", WVO = "Secondary", WEC = "Special",
WEB = "Vocational (MBO)", WHW = "Higher education")
# current institutions (no end date), one row each, with a readable sector
institutions <- institutions |>
filter(is.na(EINDDATUM)) |>
distinct(VESTIGINGSCODE, .keep_all = TRUE) |>
mutate(sector = unname(sectors[WET])) |>
select(VESTIGINGSCODE, sector, school = VOLLEDIGE_NAAM)
# current location -> recognized institution, one institution per location
link <- relations |>
filter(is.na(EINDDATUM)) |>
select(ONDERWIJSLOCATIECODE, VESTIGINGSCODE) |>
inner_join(institutions, by = "VESTIGINGSCODE") |>
distinct(ONDERWIJSLOCATIECODE, .keep_all = TRUE)
# inner join drops every location without a recognized institution
schools <- inner_join(locations, link, by = "ONDERWIJSLOCATIECODE")
nrow(schools)
#> [1] 9714
count(schools, sector)
#> sector n
#> 1 Higher education 67
#> 2 Primary 7248
#> 3 Secondary 1485
#> 4 Special 714
#> 5 Vocational (MBO) 200Only the locations backed by a recognized institution remain — no training venues, no exam halls — and each carries its school name and education sector.
One quirk worth knowing: a university or college is registered as a single recognized institution, so only its official location appears here, not its every building. The map below is therefore dominated by primary and secondary schools, which register each site.
Link the schools to the BAG
Each DUO location carries GPS coordinates, but it also carries
something better: a BAG_ID. That id points straight at the
BAG verblijfsobject, so instead of trusting DUO’s
coordinates we can fetch the authoritative BAG position of every school
with a server-side filter (see Filtering data by attribute).
The ids are nationwide, so we first narrow down to the city of
Utrecht with DUO’s own place name. That leaves a modest list of ids for
%in%; had there been thousands, pdok_where()
would send them in batches of 300 and pdok_read() would
combine the results just the same. We also drop the locations without a
BAG id: a missing value cannot be matched by the server, so
pdok_where() refuses a vector that holds one. (DUO’s table
also carries a few hundred ids that are not 16-digit BAG ids at all;
those simply match nothing.)
ids <- schools |>
filter(PLAATSNAAM == "Utrecht", !is.na(BAG_ID)) |>
pull(BAG_ID)
length(ids)
#> [1] 163
units <- pdok_read(
"kadaster/bag", "verblijfsobject",
filter = pdok_where(identificatie %in% ids)
)
nrow(units)
#> [1] 163The result is one BAG point per school, in the BAG’s own coordinates. A join on the id brings the school name and sector across (row order follows the service, so join rather than bind):
utrecht_schools <- units |>
inner_join(
select(schools, BAG_ID, school, sector, STRAATNAAM),
by = c(identificatie = "BAG_ID")
)
utrecht_schools |>
st_drop_geometry() |>
count(sector)
#> # A tibble: 5 × 2
#> sector n
#> <chr> <int>
#> 1 Higher education 7
#> 2 Primary 106
#> 3 Secondary 26
#> 4 Special 19
#> 5 Vocational (MBO) 5For the maps we also want the municipal boundary and its districts from CBS.
gemeenten <- pdok_read(
"cbs/gebiedsindelingen", "gemeente_gegeneraliseerd", datetime = 2025
)
utrecht <- filter(gemeenten, statnaam == "Utrecht")
tmap_mode("plot")
#> ℹ tmap modes "plot" - "view"
#> ℹ toggle with `tmap::ttm()`
tm_shape(utrecht) +
tm_polygons(fill = "grey95", col = "grey60") +
tm_shape(utrecht_schools) +
tm_dots(
fill = "sector", size = 0.5,
fill.scale = tm_scale_categorical(values = "brewer.set2"),
fill.legend = tm_legend("Sector")
) +
tm_title("Recognized schools in Utrecht, by sector")
Map the school buildings
Each school sits in a building from the BAG, and the BAG tells us
which one: every verblijfsobject carries a
pand.href column linking to its building.
pdok_read_href() follows those links. It reads each linked
building once, one small request each, so nothing else is downloaded,
and attaches it to the school that links to it. Think of it as a join:
the result is the schools table with the building’s columns alongside
and the building footprint as its geometry. We cannot use
pdok_where() here as we did for the units: a
verblijfsobject does not carry its building’s
identificatie, only the link, and the id in the link is
internal to the server. Following the link is the only way across. This
scales to any list: all schools in the Netherlands are roughly 9,000
links, which take about a quarter of an hour at the default,
deliberately modest request rate.
school_buildings <- pdok_read_href(utrecht_schools, "pand")
nrow(school_buildings)
#> [1] 167A few schools share a building and a few occupy two, so the row count
differs slightly from the number of schools. Columns that both BAG
layers have, such as identificatie, carry the
pand. prefix on the building side:
select(school_buildings, school, pand.identificatie, bouwjaar) |>
head(3)
#> Simple feature collection with 3 features and 3 fields
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: 5.096876 ymin: 52.09838 xmax: 5.101278 ymax: 52.11993
#> Geodetic CRS: WGS 84
#> school pand.identificatie bouwjaar
#> 1 Auris De Taalkring 0344100000081952 1970
#> 2 Auris De Taalkring 0344100000081953 1970
#> 3 Hair Kappersopleiding 0344100000054622 1904
#> geometry
#> 1 POLYGON ((5.097293 52.11974...
#> 2 POLYGON ((5.097293 52.11974...
#> 3 POLYGON ((5.100588 52.09866...For the map we zoom in on the historic center, using the CBS districts:
wijken <- pdok_read(
"cbs/gebiedsindelingen", "wijk_gegeneraliseerd", datetime = 2025,
filter_by = utrecht, predicate = "within"
)
binnenstad <- filter(wijken, grepl("Binnenstad", statnaam))
center_buildings <- pdok_filter_by(school_buildings, binnenstad)
nrow(center_buildings)
#> [1] 11The result is real school buildings, colored by sector. Click one for the school that uses it.
tmap_mode("view")
#> ℹ tmap modes "plot" - "view"
tm_basemap(pdok_basemap("grijs")) +
tm_shape(center_buildings) +
tm_polygons(
fill = "sector",
fill.scale = tm_scale_categorical(values = "brewer.set2"),
fill.legend = tm_legend("Sector"),
col = "grey30", lwd = 0.5, id = "school",
popup = tm_popup(vars = c("School" = "school", "Sector" = "sector",
"Street" = "STRAATNAAM"))
) +
tm_credits("Kaartgegevens © Kadaster")Where to next
-
Filtering data by
attribute — the
identificatie %in% idspattern used here, and the rest ofpdok_where(). -
Filtering data by area — more
on
pdok_filter_by(). -
Mapping buildings by construction
year — another BAG example, using the
pand(building) layer. - PDOK basemaps — the gray background map used here, and the other styles.