Introduction to the sf Package

DMgtAsia · Session-III

The Simple Features standard

  • sf implements Simple Features, the ISO standard for representing geometry.
  • An sf object is a data frame with a special geometry column.
  • So spatial data is just tidy data with a place attached: one row per feature, columns of attributes, plus geometry.

Live R cells on this page run in your browser via webR. The first cell takes a few seconds while sf loads; after that they are quick.


Geometry types

  • POINT a single location (a clinic, a case).
  • LINESTRING a path (a road, a river).
  • POLYGON an area (a district, a PHC catchment).
  • Each has a MULTI form (MULTIPOLYGON for a state made of many parts).

Build an sf object (live)

Press Run. We make points for four cities, then attach geometry.

Note the geometry column and the printed CRS header.


Quiz: making an sf object


Coordinate reference systems

  • A CRS tells R what the coordinates mean.
  • Geodetic (EPSG:4326, WGS 84): longitude/latitude in degrees. Good for storage and web maps.
  • Projected (a UTM zone such as EPSG:32643): metres on a flat plane. Needed for distances and areas.

Inspect and transform (live)

The numbers change from degrees to metres after st_transform().


Quiz: what is EPSG:4326?


Plot an sf object (live)

geom_sf() reads the geometry column directly. The same layer draws points, lines, or polygons.


Reading spatial files

In RStudio you read a shapefile or GeoJSON from disk:

library(sf)
library(here)
india <- st_read(here("spatial_files", "India_State_Boundary.shp"))
st_crs(india)

You do this in Exercise 1. We keep file reading in RStudio because the data files are large for a browser session.


What runs live, and what does not

  • Live in the browser (webR): sf core, st_as_sf, st_crs, st_transform, geom_sf.
  • Run in RStudio (static here):
    • Raster extraction (exactextractr, raster) in Exercise 3.
    • Geocoding (tidygeocoder) in Exercise 4.
    • Spatial weights and clustering (spdep, rgeoda, Moran’s I, LISA) in Session-IV.

These packages are not yet built for WebAssembly, so they stay in the desktop exercises.


Hands-on for this session

  • Exercise 1 load and plot India shapefiles; check and transform CRS.
  • Exercise 2 a medical-college choropleth; joins and case_when name harmonisation.
  • Exercise 3 raster extraction (population per state).
  • Exercise 4 geocoding medical colleges.

Each is an R script you run in RStudio.

Recap

  • sf is tidy data with a geometry column.
  • Geometry types: point, line, polygon, and their multi forms.
  • st_as_sf builds geometry; st_crs reads it; st_transform reprojects.
  • geom_sf maps it.
  • Heavier tools (raster, geocoding, clustering) run in RStudio and in Session-IV.