library(curl)
# Extracting relevant columns from the 'voters' dataset
to_send = voters[,c("sosidnum", "street", "city", "zip")]
# Renaming the columns
to_send = setNames(to_send, c("Unique ID", "Street Address", "City", "Zip"))
# Adding a new column for the state
to_send$State = "OH"
# Rearranging the columns
to_send = to_send[, c("Unique ID", "Street Address", "City", "State", "Zip")]
# Creating a temporary file to store the data in CSV format
t = tempfile(tmpdir = getwd(), fileext = ".csv")
# Writing the data to the CSV file
write.csv(to_send, t, row.names = FALSE)
# Creating a new handle for making a request
h <- new_handle() |>
handle_setform(
addressFile = form_file(t),
benchmark = "Public_AR_Current"
)
# Sending a POST request to geocode the addresses
x = curl_fetch_memory("https://geocoding.geo.census.gov/geocoder/locations/addressbatch", handle = h)
# Removing the temporary file
file.remove(t) |> invisible()
# Creating a new temporary file to store the response
t = tempfile(tmpdir = getwd(), fileext = ".csv")
# Writing the response content to the temporary file
x$content |> rawToChar() |> cat(file = t)
# Reading the response into the 'results' dataframe
results <- read.csv(t, header = F, col.names = c("uid", "address", "match", "match_type", "matched_address", "latlon", "tigerid", "tigerside"))
# Removing the temporary file
file.remove(t) |> invisible()
head(results)