0

I have a dataset of ~60,000 observations with a latitude column and longitude column.

Is there a function that can tack on a "county fipscode" column?

  • 1
    You may use a web API with R package `httr`, see https://stackoverflow.com/questions/5864601/find-county-name-for-a-lat-long. –  Feb 10 '22 at 17:01
  • Another approach with `sf` and `spData` packages: https://stackoverflow.com/questions/8751497/latitude-longitude-coordinates-to-state-code-in-r/8751965#8751965 – Grzegorz Sapijaszko Feb 10 '22 at 18:56
  • @GrzegorzSapijaszko I'm looking at this answer, which is very related. https://stackoverflow.com/questions/13316185/r-convert-zipcode-or-lat-long-to-county However, I'm struggling to see how I would use that on an entire dataframe and make a column name out of the county FIPS codes – Tobin Brooks Feb 10 '22 at 18:59
  • @GrzegorzSapijaszko Oh I think I got it. I had to switch the order the latitude and longitude columns were in! My only last issue is that now I have a column that gives "state, county" Would really love to get the county fips code as well – Tobin Brooks Feb 10 '22 at 19:11
  • I would start with `tigris` package, get all the countries with `counties()` function, then find those county which overlaps with point (`st_within` from `sf`). You can build a small function and then mutate it on you data frame like: `CntFIP <- function(point, counties) { a <- sf::st_within(point, counties); if(length(a[[1]]) == 0L) { FIPS = NA; } else { FIPS <- counties[a[[1]],"COUNTYFP"]; FIPS <- FIPS$COUNTYFP; } return(FIPS); } ` – Grzegorz Sapijaszko Feb 10 '22 at 20:12
  • @GrzegorzSapijaszko I'm using the following code `library(usmap)` `lapply(split(df, df$state), function(x)` `fips(state = x$state[1], county = x$county)) ` https://stackoverflow.com/questions/62271722/from-state-and-county-names-to-fips-in-r this prints out the fips of all my counties. But I'm getting errors when I try to turn this into a dataframe column – Tobin Brooks Feb 10 '22 at 21:20
  • @TobinBrooks, open a new question please, putting sample of your data frame if possible. – Grzegorz Sapijaszko Feb 10 '22 at 22:03

0 Answers0