For some research I am working on, I have a dataframe called
charters of charter schools in New Jersey. Simplified it looks like this:
school.name school.id district.id lat lon oceanside charter school 008229 3400011 39.3635 -74.4350 discovery charter school 228881 3400020 40.7343 -74.1745
I also have a SpatialPolygonsDataFrame of school districts in New Jersey which I got through the Tigris package:
nj.school.districts <- tigris::school_districts("NJ"). For regular, non-charter schools, their
district.id matches their geographic district.id, as one might expect. However, for charter schools a unique
district.id is assigned that doesn't reflect their geographic location at all.
My goal is to assign a
geographic.district.id to each school in
charters that reflects the district it is actually located in. The
nj.school.districts spdf looks like this:
So there are 342 districts, each with a unique
GEOID. It is this
GEOID that should be assigned to each charter school that falls within the district. I've mapped the charters over the school districts so could do it manually that way, but in reality it would be too time consuming.
I've been able to extract the coordinates of a particular polygon, and to confirm whether or not any schools are in it through this code:
nj.polygon1.coords <- as.data.frame(nj.school.districts@polygons[]@Polygons[]@coords) %>% select(lat = V2, lon = V1) xp = as.vector(nj.polygon1.coords$lon) yp = as.vector(nj.polygon1.coords$lat) in.poly <- pracma::inpolygon(charters$lon, charters$lat, xp, yp)
but I don't know how to do it at scale or how to then assign the new
tigris(CA is being very slow to download now...). If your school data is already broken down by state then looping over state should be fairly efficient - creating a single whole-US boundary file might get large.