Skip to contents

This function extracts coordinates from an sf object's geometry and adds them as new columns to the object.

Usage

add_coordinates(sf_object, lon = "lon", lat = "lat")

Arguments

sf_object

An sf object containing spatial features.

lon

A string specifying the name of the longitude column. Defaults to "lon".

lat

A string specifying the name of the latitude column. Defaults to "lat".

Value

An sf object with the added coordinate columns.

Examples

# Load necessary packages
library(sf)
library(dplyr)

# Create a simple sf object
points <- data.frame(
  name = c("A", "B"),
  geometry = c("POINT(1 2)", "POINT(3 4)")
) %>%
  st_as_sf(wkt = "geometry")

# Add coordinates using default column names
points_with_coords <- add_coordinates(points)

# Add coordinates using custom column names
points_with_coords_custom <- add_coordinates(points, lon = "longitude", lat = "latitude")