0Pricing
R Academy · Lesson

Simple Features with the sf Package

Read, write, and manipulate spatial geometries using the sf standard.

What Is the sf Package?

The sf (Simple Features) package is R's primary tool for geospatial vector data. It stores geometries (points, lines, polygons) as a special list column in a regular data frame, making it fully compatible with dplyr and ggplot2.

library(sf)

# sf data frames look like regular data frames
# but have a special 'geometry' column
cat('sf version:', packageVersion('sf'), '\n')

# Supported geometry types
cat('Geometry types: POINT, LINESTRING, POLYGON,\n')
cat('               MULTIPOINT, MULTILINESTRING, MULTIPOLYGON,\n')
cat('               GEOMETRYCOLLECTION\n')

read_sf: Loading Shapefiles

read_sf("file.shp") reads any OGR-supported format (Shapefile, GeoJSON, GeoPackage, KML, etc.) into an sf object. It automatically reads the CRS and attribute table alongside the geometries.

library(sf)

# Read a GeoJSON file from a URL
url <- 'https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson'

# For demonstration, use the system example data
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

cat('Class:', class(nc), '\n')
cat('Dimensions:', nrow(nc), 'rows x', ncol(nc), 'cols\n')
cat('CRS:', st_crs(nc)$epsg, '\n')
cat('Geometry type:', unique(st_geometry_type(nc)), '\n')
cat('Column names:', paste(names(nc)[1:5], collapse = ', '), '...\n')

All lessons in this course

  1. Simple Features with the sf Package
  2. Coordinate Reference Systems and Projections
  3. Spatial Joins and Operations
  4. Interactive Maps with leaflet
← Back to R Academy