Spatial workflows

Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.

spbalance

Balance a spatial panel by retaining common time periods

Stata

spbalance, balance

R Package:base

{ counts <- table(data$time); common <- as.numeric(names(counts)[counts == length(unique(data$id))]); data[data$time %in% common, , drop = FALSE] }

Differs from Stata Fixed workflow; adapt the named data columns explicitly. Requires unique unit/time pairs. Mirrors spbalance’s choice to drop incomplete time periods while retaining spatial units; it does not fill missing outcomes.

spdistance

Distance between two identified planar locations

Stata

spdistance 1 2

R Package:base

sqrt(sum((as.numeric(data[data$id == 1, c("x", "y")]) - as.numeric(data[data$id == 2, c("x", "y")]))^2))

Differs from Stata Fixed workflow; adapt the named data columns explicitly. Planar Euclidean distance only; longitude/latitude require a geodesic calculation and explicit units.

spgenerate

Compute a spatially lagged covariate

Stata

spgenerate nearby = W*value

R Package:base

drop(W %*% data$value)

Differs from Stata Fixed workflow; adapt the named data columns explicitly. W must use the identical unit ordering as data; this operation does not fit a spatial autoregressive model.

spmatrix

Row-standardized inverse-distance spatial weights

Stata

spmatrix create idistance W, normalize(row)

R Package:stats

{ D <- as.matrix(stats::dist(data[c("x", "y")])); W <- matrix(0, nrow(D), ncol(D)); off <- row(D) != col(D); W[off] <- 1 / D[off]; W / rowSums(W) }

Differs from Stata Fixed workflow; adapt the named data columns explicitly. Planar distances, distinct non-coincident locations and matching row/column ID order are required. Stata defaults to spectral normalization, so row normalization is explicit.

spset

Declare planar point geometry and coordinate reference system

Stata

spset id, coord(x y)

R Package:sf

sf::st_as_sf(data, coords = c("x", "y"), crs = 3857, remove = FALSE)

Differs from Stata Fixed workflow; adapt the named data columns explicitly. Creating an sf object does not set Stata dataset metadata. Coordinates and CRS must describe the actual data; do not assign a projected CRS to longitude/latitude.