Learn R Programming

linkeR (version 0.1.2)

process_sf_data: Process SF Data for Leaflet Integration

Description

process_sf_data is a helper function to extract coordinates from an sf object or ensure lng/lat columns exist in a data frame.

Usage

process_sf_data(data, lng_col = "longitude", lat_col = "latitude")

Value

Data frame with explicit lng/lat columns, ready for leaflet integration

Arguments

data

Data frame or sf object. If sf object, coordinates will be extracted.

lng_col

Character string. Name for the longitude column (default: "longitude")

lat_col

Character string. Name for the latitude column (default: "latitude")

Details

This function handles three scenarios:

  • SF objects: Extracts coordinates using sf::st_coordinates() and creates lng/lat columns

  • Regular data frames with existing lng/lat columns: Returns unchanged

  • Regular data frames without lng/lat columns: Issues warning and returns unchanged

For sf objects, the function:

  • Extracts point coordinates from the geometry column

  • Adds coordinates as new columns with the specified names

  • Preserves the original geometry column for advanced spatial operations

  • Returns an sf object with both geometry and coordinate columns

Examples

Run this code
if (requireNamespace("sf", quietly = TRUE)) {
  # Create a sample sf object
  sf_data <- sf::st_as_sf(
    data.frame(
      id = 1:2,
      name = c("A", "B"),
      geom = c("POINT(-111.9 40.7)", "POINT(-111.8 40.6)")
    ),
    wkt = "geom",
    crs = 4326
  )

  # Process the sf object
  processed_data <- process_sf_data(sf_data)
  print(processed_data)
}

Run the code above in your browser using DataLab