OpenStreetMap & neighbourhood effects

TN Square Day 1 – October 28, 2026 – Afternoon session

Maël Lecoursonnais |
Maria Brandén |

The afternoon

Time What
14.00-14.30 Slides: R, spatial data, OpenStreetMap, a worked example
14.30-15.30 Lab: universities in Stockholm, distance, merge with register data
15.30-16.00 Own work, in groups
16.00-16.30 Break
16.30-17.00 Own work, in groups
17.00-17.30 Presentations (5 min per group)

The question for today:

  • How to retrieve data from OpenStreetMap.
  • Is the distance to the nearest university associated with the share of pupils choosing an academic track in upper secondary school?
  • Builds on Lecoursonnais et al. (2025), The Spatial Determinants of Academic Aspirations: Evidence From Sweden

Before we start

  1. R and RStudio (or Positron) installed.
  2. The packages installed (next slides).
  3. The data folder downloaded and unzipped in a project folder.

Everything is on https://maellecoursonnais.github.io/tn-square: the slides, the lab and the data.

New to R? Pair with someone who is not.

1. R in a nutshell

R, RStudio/Positron, projects

  • R is the language; RStudio or Positron is the editor you write it in.
  • Work in a folder. In RStudio: File > New Project. In Positron: Open Folder. Your working directory is the project folder, so paths stay short and portable.
TN-lab/
├── slides.html       <- the slides you are reading
├── lab.html          <- your notebook
└── data/
    ├── deso_stockholm.gpkg       <- DeSO polygons, Stockholm County
    ├── deso_stockholm_data.csv   <- register data, municipality of Stockholm
    ├── kommun_stockholm.gpkg     <- municipality borders
    ├── uni_osm.rds               <- backup of the OSM query
    └── uniPoly.RData             <- universities, cleaned by hand (paper)
  • Read files with relative paths: read_sf("data/deso_stockholm.gpkg"), never C:/Users/....

Packages

Install once, load every session:

install.packages(c("tidyverse", "sf", "osmdata", "tmap"))

library(tidyverse) # data wrangling + ggplot2
library(sf)        # spatial data frames ("simple features")
library(osmdata)   # query OpenStreetMap
library(tmap)      # static and interactive maps

Maps: tmap (version 4), with tmap_mode("plot") for static maps and tmap_mode("view") for interactive ones. The same code works in both modes.

  • Help: ?st_distance, or the package vignettes (vignette("osmdata")).
  • Errors are normal. Read the message, then search it.

The pipe and the tidyverse

deso_data |>                                   # take the data, then
  filter(!is.na(share_academic)) |>            # keep the DeSOs with data, then
  mutate(rich = mean_income_rank > 0.5) |>     # create a new variable, then
  group_by(rich) |>                            # for each group,
  summarise(n_deso = n(),                      # summarise it
            share_academic = mean(share_academic))
# A tibble: 2 × 3
  rich  n_deso share_academic
  <lgl>  <int>          <dbl>
1 FALSE    180          0.725
2 TRUE     309          0.875
  • |> (or %>%, the older pipe from magrittr) reads as “and then”.
  • Main dplyr verbs: filter(), select(), mutate(), group_by() + summarise(), left_join().

2. Spatial data in R

sf: a data frame with a geometry column

Attributes: an ordinary data frame Geometry: where it is
name_long continent pop (M) geom
Sweden Europe 9.7 MULTIPOLYGON (((11.03 58.8...
Italy Europe 60.8 MULTIPOLYGON (((8.71 40.9,...
Brazil South America 204.2 MULTIPOLYGON (((-53.37 -33...

+ a CRS: how to read the coordinates (here WGS 84, in degrees)

  • One row = one feature (a country, a neighbourhood, a university…).
  • All dplyr verbs work; the geometry “sticks” to the rows.
  • Spatial functions start with st_: st_distance(), st_join(), st_intersects(), st_buffer(), st_centroid()…

Points, lines, polygons

  • Points: a university’s entrance, a bus stop, the centroid of a spatial unit.
  • Lines: roads, rivers, railways.
  • Polygons: a neighbourhood, a municipality, a campus.
  • Multipolygons: one feature, several pieces (islands, a campus split by a road).

Coordinate reference systems (CRS)

Every flat map distorts something. Pick the CRS for the job:

CRS EPSG Units Use
WGS 84 4326 degrees GPS
Web Mercator 3857 metres Web map tiles (OSM)
Equal Earth 8857 metres World maps of areas
SWEREF99 TM 3006 metres Distances in Sweden

In R:

st_crs(deso)                       # check
deso_wgs84 <- st_transform(deso, 4326)  # convert

3. OpenStreetMap

What is OpenStreetMap?

  • A free, open map of the world, built by volunteers (the Wikipedia of maps).
  • Every object is described by tags: key = value pairs.
  • Data comes from the Overpass API, which osmdata wraps for you.

Keys and values

  • The key is the category, the value is the type within the category.
  • One key has many values; the same value can appear under different keys.
Key Values (examples)
amenity university, school, library, kindergarten, community_centre, place_of_worship services and facilities used by residents
leisure park, playground, sports_centre leisure
shop supermarket, convenience, bakery shops
highway bus_stop, primary, residential roads and stops
building university, school, apartments, house

Accessing OSM data in R

uni <-
  getbb("Stockholm Municipality") |>          # 1. Bounding box           
  opq(timeout = 300) |>                       #    ... build the query
  add_osm_feature(key = "amenity",            # 2. Features: key and value
                  value = "university") |>
  osmdata_sf()                                # 3. Convert to sf

The result is a list of several sf objects:

uni$osm_points          # single points (+ vertices of polygons)
uni$osm_polygons        # campuses drawn as areas
uni$osm_multipolygons   # complex areas

Note

OSM is collaborative, so the data is messy. Always map and inspect what you got.

The Overpass server limits the number of queries per IP. If you get HTTP 429, wait or switch server: set_overpass_url("https://overpass.kumi.systems/api/interpreter").

Points or polygons?

  • A campus is an area, not a point. KTH covers 33 hectares.
  • Polygons are richer: distance to the edge of the campus, whether a DeSO touches a campus, the area of campuses nearby.
  • But only 5 of the 13 universities in Stockholm County are drawn as areas in OSM.
DeSOs in Stockholm
Median, to point (km) 5.07
Median, to polygon (km) 4.98
Max difference (km) 1.52

st_distance() works the same way with points and polygons: for polygons, it measures to the closest edge.

Your turn (5 min): check your surroundings

Is OSM right about the place you know best?

  1. Go to openstreetmap.org and zoom in on where you live, grew up, or work.
  2. Use the “Query features” tool (the ? button on the right) to click on objects and see their tags.
  3. Or, in R, with a small bounding box:
getbb("Your neighbourhood, Your city") |>
  opq() |>
  add_osm_feature(key = "amenity", value = "school") |>
  osmdata_sf()
  • Are your school, library, park there? Correctly tagged?
  • What is missing? Would it be missing everywhere, or only in some places?

4. Example: universities in Sweden

Step 1 – Query all universities in Sweden

uni_se <-
  getbb("Sweden", featuretype = "country") |>
  opq(timeout = 600) |>
  add_osm_feature(key = "amenity", value = "university") |>
  osmdata_sf()

# Points, polygons and multipolygons, with a name, in one sf object
uni_raw <-
  unique_osmdata(uni_se)[c("osm_points", "osm_polygons", "osm_multipolygons")] |>
  bind_rows() |>
  filter(!is.na(name)) |>
  select(osm_id, name, geometry) |>
  st_as_sf() |> 
  mutate(geometry = unname(geometry)) |> # drop names or tmap fails
  st_make_valid() # Some polygons are invalid

Note

The query for the whole of Sweden takes several minutes, and the server does not like 30 people sending it at the same time. We ran it (and cleaned it) for the paper: the result is uniPoly.RData, in the data folder. All the maps of Sweden below use it.

Step 2 – Look at it

tmap_mode("view")                                  # interactive map

tm_shape(uni_raw) +
  tm_polygons(fill = "blue", fill_alpha = 0.3, id = "name") + 
  tm_dots(fill = "blue", size = 0.5, id = "name")             

What goes wrong?

  • Features outside Sweden: the bounding box is a rectangle (Norway, Finland, Åland…).
  • The same campus many times: each building can be its own feature.
  • Things that are not universities: folk high schools, exam halls, student health centres, research stations…
  • Inconsistent names: “Stockholms konstnärliga högskola” vs. “Stockholms Konstnärliga Högskola”.

You will see all of this for Stockholm in the lab!

Step 3 – Clean

What we did for the paper (simplified):

uni_clean <- uni_raw |>
  st_make_valid() |>
  st_transform(3006) |>        # SWEREF99 TM, in metres
  st_filter(sweden) |>         # only features within Sweden
  st_join(municipalities)      # add municipality code and name

# One campus is often drawn as many buildings:
# merge the features that are within 1 km of each other
clusters <- uni_clean |> st_buffer(500) |> st_union() |> st_cast("POLYGON")
uni_clean$cluster <- unlist(st_intersects(uni_clean, clusters))

uniPoly <- uni_clean |>
  group_by(cluster) |>
  summarise(name = first(name)) |>  # summarise() merges the geometries
  left_join(classification)         # by hand: type of institution, year of creation

save(uniPoly, file = "data/uniPoly.RData")

Data processing is the tricky part

Every step above is a choice, and each one can change the results:

Choice Options Why it matters
What is a university? Universities only, + colleges, + art schools, + research stations Changes who is “close”
What is one campus? Same name, within 500 m, within 1 km Number of campuses around a DeSO
Where is a campus? Centroid, point on surface, polygon The distance itself
Which years? Today’s campuses, or those open when pupils were 15 Universities open and close

Tip

Some of these choices are made by hand. Look at your data, write down what you did and why, and check whether the results change.

Step 4 – The result: uniPoly

load("data/uniPoly.RData")
uni_pts <- st_point_on_surface(uniPoly)
  • 50 campuses, each with its name, municipality, type and year of creation, added by hand.
  • The geometry is a polygon when OSM draws the campus as an area, a point otherwise.

Step 4 – The expansion of higher education

Step 5 – Distance from each DeSO to the nearest campus

deso_pts <- st_point_on_surface(deso_se)          # one point per DeSO
nearest  <- st_nearest_feature(deso_pts, uni_pts) # index of the closest campus

deso_se <- deso_se |>
  mutate(nearest_uni = uni_pts$name[nearest],
         dist_km = as.numeric(st_distance(deso_pts, uni_pts[nearest, ],
                                          by_element = TRUE)) / 1000)

summary(deso_se$dist_km)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
  0.05835   3.62497  11.13232  20.97219  30.70308 291.34390 
  • st_point_on_surface() rather than st_centroid(): the centroid of an odd-shaped DeSO can fall outside it.
  • st_nearest_feature() gives the row number of the nearest campus; st_distance(..., by_element = TRUE) the distance to it, in metres (the unit of the CRS).

Step 5 – Map

More resources

Your turn

Open the lab: https://maellecoursonnais.github.io/tn-square/lab.html.

New to R? pair with someone who is not!

At 16.00, extend the analysis your own way. At 17.00, present your findings in 5 minutes.