1

I want to combine voter precinct data with school zone data. Precinct boundaries do not line up neatly with school zone boundaries in all cases.

Code look something like this:

library(rgdal)
library(tigris)
library(sf)

precincts <- readOGR(
  dsn = "input/SOEShapefiles2020/SOEShapefiles2020.shp",
  layer = "SOEShapefiles2020"
)

precinctDemos <- read.csv("input/data/Party registration in voting precincts.csv")
mPrecDemo <- geo_join(
  spatial_data = precincts,
  data_frame = precinctDemos,
  by_sp = "PRECINCT",
  by_df = "Precinct",
  how = "inner"
)

elemZones <- readOGR(
  dsn = "input/2020-21_Attendance_Boundaries/2020-21_ElemAttendance.shp",
  layer = "2020-21_ElemAttendance"
)
elemZones$MSID_ELEM <- as.numeric(elemZones$MSID_ELEM)
attendance <- read.csv("elementary school attendance.csv")

mElem <- geo_join(
  spatial_data = elemZones,
  data_frame = attendance,
  by_sp = "MSID_ELEM",
  by_df = "School.",
  how = "inner"
)

So mElem and mPrecDemo are each "Large SpatialPolygonsDataFrame" objects. How do I perform a spatial join to bring the two objects together? I want to be able to estimate the number of voters in each school zone.

1 Answer 1

1

Package sf (simple features) makes it easier and more understandable to deal with spatial objects in R; besides that, it reads shapefiles in way faster than readOGR and returns these data.frame like objects of sf class.

In your case, just converting the two SpatialPolygonsDataFrame and joining spatially would be like this:

library(sf)
mPrecDemo = st_as_sf(mPrecDemo)
mElem = st_as_sf(mElem)
st_join(mPrecDemo, mElem) 

In this case, you get the features of the first with the data of the spatially intersecting feature, if any. Check ?st_join to see the available predicates.

For translating the rest of your code into sf :

library(sf)
library(dplyr)
precincts <- read_sf("input/SOEShapefiles2020/SOEShapefiles2020.shp")

precinctDemos <- read.csv("input/data/Party registration in voting precincts.csv")

# I think you are rather looking for a left_join, otherwise just change for inner_join
mPrecDemo <- left_join(precincts, precinctDemos, by = c("PRECINCT" = "Precinct"))

elemZones <- read_sf("input/2020-21_Attendance_Boundaries/2020-21_ElemAttendance.shp")

elemZones$MSID_ELEM <- as.numeric(elemZones$MSID_ELEM)
attendance <- read.csv("elementary school attendance.csv")

mElem <- left_join(elemZones, attendance, by = c("MSID_ELEM" = "School."))

st_join(mPrecDemo, mElem)
2
  • I got this error: Error in st_geos_binop("intersects", x, y, sparse = sparse, prepared = prepared, : st_crs(x) == st_crs(y) is not TRUE.
    – Username
    Nov 11, 2020 at 0:31
  • 1
    so you must re-project one layer, you can try: mElem = st_transform(mElem, st_crs(mPrecDemo))
    – Elio Diaz
    Nov 11, 2020 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.