0.field buffer.R

0.field buffer.R

0.field buffer.py

0.field buffer.R

0.field buffer.py

library(sf)
import geopandas as gpd

Loads a library for handling geospatial data, including working with shapefiles.

In the Python code, gpd is an alias for the geopandas library Using the alias simply reduces typing and improves code readability.

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

 

RStudio defaults to a global working directory, which means file paths must be specified explicitly.

Python defaults to the folder where the source code is located.

Jupyter Notebook defaults to where you launch the notebook server.

  • You could launch it from the command line within the source folder:

  • Or you could specify the folder directly when launching Jupyter:

The original file path was "E:/Eastern_Shore/MD_enrollment_data_2023_24/fields/", but I don't have access to that location.

To avoid referencing "E:/Eastern_Shore..." explicitly, I saved all the necessary project files to the same folder as the source code, and I added a setwd() statement to the R source. I then removed all references to "E:/Eastern_Shore..."

This way, the R program can run without requiring the full path in filenames.

This code:

  • Reads a shapefile into a spatial data frame (R) or a GeoDataFrame (Python).

  • Converts the coordinate reference system (CRS) to EPSG 32618 (WGS 84).

  • Applies a negative buffer of 30 meters to shrink the geometries.
    Note that sf objects in R have a designated geometry column, but in GeoPandas you need to explicitly reference the geometry column.

  • Filters out any empty geometries resulting from the buffering.
    In Python, ~ is a bitwise NOT operator.

R uses %>% for chaining operations, while Python uses . (dot notation).

In Python, a backslash (\) means line continuation. I used it here to align the code with the R version. But I could have also written it as:
mda = gpd.read_file("MDAEnrollment2023-2024.shp").to_crs(epsg=32618)

Also, note that the dots in st_transform(., crs = 32618) and st_buffer(., dist = -30) are optional but may improve readability.

Writes the buffered data frame to a new shapefile.

I added append=FALSE to the original source so the file would be overwritten if it exists. GeoPandas automatically overwrites existing files.