Geocoding Using NY Geocoder and Finding NY Political Districts Using R
Geocoding Using NY Geocoder and Finding NY Political Districts Using R
I re-wrote my Python script for coding political districts in NY using R and the ArcGIS Feature Services containing the political districts. This is a much more elegant approach then using Python, as it is self-contained and geocodes 750 records at a time, so large files that contain more then 1,000 records can be used with this script to be geocoded. You could just modify this script for purposes of getting coordinates, and skip the section that figures out what district persons live in.
library(tidyverse)
library(httr)
library(sf)
rm(list=ls())
# get district lines from nys gis
cd <- arcpullr::get_spatial_layer('https://gisservices.its.ny.gov/arcgis/rest/services/NYS_Congressional_Districts/FeatureServer/0')
sd <- arcpullr::get_spatial_layer('https://gisservices.its.ny.gov/arcgis/rest/services/NYS_Senate_Districts/FeatureServer/0')
ad <- arcpullr::get_spatial_layer('https://gisservices.its.ny.gov/arcgis/rest/services/NYS_Assembly_Districts/FeatureServer/0')
# read file
df <- openxlsx::read.xlsx('~/Downloads/addresses.xlsx') %>%
janitor::clean_names()
# clean up data, remove " and return characters which will break the
# json query and choke geocoder, convert to single line
df <- df %>%
mutate(
'OBJECTID' = row_number(),
'SINGLELINE' = paste(str_replace(address, '-\\d+ ', ' ') %>% str_replace_all("[\r\n]",'') %>% str_replace_all('"', '\\"') %>% str_trim(),
str_replace(municipality,'\\(.*?\\)',''), state, zip_code, sep = ', '),
)
# temporary tibble for storing geocoded addresses
res_df <- tibble()
# geocode 750 records at a time
for (i in seq(1, nrow(df), 750)) {
# keep from over-running the dataframe
j <- i + 749
j <- ifelse(j > nrow(df), nrow(df), j)
# build json for query
query <- str_c(
'{ "attributes": { "OBJECTID": ', df[i:j, 'OBJECTID'],
', "SINGLELINE": "', df[i:j, 'SINGLELINE'],
'" } },', collapse = '\n')
query <- str_c('{"records": [', query, ']}', sep='\n')
post <- list( 'f' = 'pjson', 'outSR' = 4326, 'addresses' = query )
url <- 'https://gisservices.its.ny.gov/arcgis/rest/services/Locators/Street_and_Address_Composite/GeocodeServer/geocodeAddresses'
# query state geocoder
res <- POST(url, body = post, encode = "multipart")
Sys.sleep(5)
# extract from json the coordinates
res_df <- bind_rows(res_df,
jsonlite::fromJSON(content(res, as='text')) %>%
as.data.frame() %>%
as_tibble() %>%
janitor::clean_names() %>%
unnest(cols = c(locations_location, locations_attributes)) %>%
select(OBJECTID = ResultID, matched_address = Match_addr,
score = locations_score, lng = x, lat = y)
)
}
# join the found coordinates from state geocoder to df
df <- df %>% left_join(res_df, by='OBJECTID')
# spatial join against cd, sd, ad
df <- df %>%
mutate(lat = ifelse(is.na(lat), 0, lat),
lng = ifelse(is.na(lng), 0, lng)) %>%
st_as_sf(coords = c("lng", "lat"),
crs=4326) %>%
st_intersection(cd) %>%
st_drop_geometry() %>%
select(OBJECTID, CD.2022 = DISTRICT, CD.2023.MEMBER = NAME) %>%
left_join(df, ., by='OBJECTID')
df <- df %>%
mutate(lat = ifelse(is.na(lat), 0, lat),
lng = ifelse(is.na(lng), 0, lng)) %>%
st_as_sf(coords = c("lng", "lat"),
crs=4326) %>%
st_intersection(sd) %>%
st_drop_geometry() %>%
select(OBJECTID, SD.2022 = DISTRICT, SD.2023.MEMBER = NAME) %>%
left_join(df, ., by='OBJECTID')
df <- df %>%
mutate(lat = ifelse(is.na(lat), 0, lat),
lng = ifelse(is.na(lng), 0, lng)) %>%
st_as_sf(coords = c("lng", "lat"),
crs=4326) %>%
st_intersection(ad) %>%
st_drop_geometry() %>%
select(OBJECTID, AD.2022 = DISTRICT, AD.2023.MEMBER = NAME) %>%
left_join(df, ., by='OBJECTID')
# output the excel spreadsheet
df %>%
select(addresses:zip_code, CD.2022:AD.2023.MEMBER, score, lat, lng, matched_address) %>%
openxlsx::write.xlsx('/tmp/geocoded_addresses.xlsx')
Schenectady – Rotterdam 1954
A look at Schenectady in 1950s before Interstate 890 bisected the city and Rice Road was the primary way people go to Exit 26 of Thruway.
Schenectady 1954: https://prd-tnm.s3.amazonaws.com/StagedProducts/Maps/HistoricalTopo/GeoTIFF/NY/NY_Schenectady_129430_1954_24000_geo.tif
Rotterdam 1954: https://prd-tnm.s3.amazonaws.com/StagedProducts/Maps/HistoricalTopo/GeoTIFF/NY/NY_Rotterdam%20Junction_129227_1954_24000_geo.tif
Jill Stein Part II
Some people are surprised that I voted for Jill Stein on the Green line for President.Β I voted for Working Families candidates down the rest of the line. Most of the races weren’t particularly competitive or interesting, but I wanted to sending a message that I want candidates in office that are working for average people.
The last three Presidential Elections I’ve voted for have been for Democrats — John Kerry, then Barack Obama’s two terms — all on the Working Families Party line. But I certainly don’t always vote for Democrats. In retrospect, I think I would have voted for George Bush on Conservative line in 2004, as I thought he showed a lot of courage during the start of the Great Recession, and I approving his 2007 energy bill did much to move our nation’s energy policies forward, including the strong new fuel economy standards, lighting energy standards and other efficiency standards that will save millions of megawatts and billions of gallons of fuel.
But I’ve always been somebody to split tickets and vote on third party lines …
On the state level In 2002, I voted for Tom Golisano for Governor who had the Independence line. In 2006, I voted for Elliot Spitzer, a Democrat for Governor then in 2010 I voted for Carl Paladino on the conservative line and also in 2014, I voted for Rob Astorino on conservative line. I’m not a real big conservative, but I do like the idea of limiting the role of government and checking the power of governor. I’ve never liked a certain governor, ever since he served in lower levels of government, nor his poorly thought out, SAFE Act.Β Down ballot, I tend to vote overwhelmingly Democratic, as I think we want local politicians that are more environmentally sensitive — especially on the planning board level. Some of the local Republicans and Conservatives, where they exist, are just awful. Most are just nuts.
I’m not aΒ big fan of voting for candidates on the major party lines.Β I want candidates to have ideas and an ideology. The Democratic and Republican Parties do good job supporting their members, but they are hardly idea factories. The minor parties force the candidates to take a stand and help express a view point. Thanks to New York’s unique fusion law, I try to vote with the minor parties whenever they run a candidate I like. And I don’t I feel like I have to be tied to any one party or ideology when it comes down to voting.
I also like aΒ divided government.Β I think public policy decisions should be taken cautiously and in general the status quo isn’t that bad. Divided government protects different regions and groups of people in our country, it ultimately protects liberty. A Republican US Senate would be an important check on Hillary’s power. Many years I do split my ticket, and while I didn’t do that this year, I am sure in future years I will keep an open mind, and maybe even vote for some Republicans like I have on state or local level in years past.
While I wouldn’t and I’m glad I didn’t vote for Hillary Clinton,Β I think it’s good news that she is the likely next president.Β She seems like a responsible individual, and it will be good to have a women president — and that our country is becoming more pluralistic and open to different groups and people. While I have reservations on some of her policy positions, I think she will do a good job. Jill Stein may be a better choice — and I’m happy having voted for her — but Hillary won’t be a bad second choice.
That’s my thoughts on the election. You are free to have your thoughts.
Hillcross Pond – Catskill Mountains
I love that OSI has purchased this land and will be added to the Rensselearville State Forest in the coming years once the state finalizes the transaction. I do hope they bush hog this area from time to time and maintain it as open fields.
Taken on Saturday October 8, 2022 at Rensselearville State Forest.2023 Primary Albany County Races – Google Sheets
I crunched the 2023 Primary Albany County Races with turn out and drop off.