Code Monkey home page Code Monkey logo

fipio's Introduction

fipio

CRAN status CRAN downloads codecov R-CMD-check MIT License

fipio is a lightweight package that makes it easy to get information about a US FIPS code.

Installation

You can install the released version of fipio from CRAN with:

install.packages("fipio")

or the development version with pak or remotes:

# Using `pak`
pak::pkg_install("program--/fipio")

# Using `remotes`
remotes::install_github("program--/fipio")

Usage

fipio makes it easy to get information about a US FIPS code. Let’s answer a few questions that might come up if you have a FIPS code:

fip <- "37129"

# What state is `37129` in?
fipio::fips_state(fip)
#> [1] "North Carolina"

# Alternatively, you can use the state FIPS code by itself
fipio::fips_state("37")
#> [1] "North Carolina"

# What about the state abbreviation?
fipio::fips_abbr(fip)
#> [1] "NC"

# What county is `37129`?
fipio::fips_county(fip)
#> [1] "New Hanover"

# It'd be nice to have this all in a data.frame...
fipio::fips_metadata(fip)
#>   state_region state_division feature_code     state_name state_abbr
#> 1            3              5      1026329 North Carolina         NC
#>          name fip_class tiger_class combined_area_code metropolitan_area_code
#> 1 New Hanover        H1       G4020                 NA                   <NA>
#>   functional_status land_area water_area fip_code
#> 1                 A 497937486  353803887    37129

# And the metadata for the state by itself...
fipio::fips_metadata("37")
#>   state_region state_division feature_code     state_name state_abbr
#> 1            3              5      1027616 North Carolina         NC
#>             name fip_class tiger_class combined_area_code
#> 1 North Carolina      <NA>       G4000                 NA
#>   metropolitan_area_code functional_status    land_area  water_area fip_code
#> 1                   <NA>                 A 125933327733 13456093195       37

With sf

fipio also includes functions that support geometry for FIPS codes. This requires sfheaders at the very least to get an sf-compatible geometry object back.

# I'm doing spatial work, what's the geometry of `37129`?
fipio::fips_geometry(fip)
#> Geometry set for 1 feature 
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -78.02992 ymin: 33.7868 xmax: -77.67528 ymax: 34.38929
#> Geodetic CRS:  WGS 84
#> MULTIPOLYGON (((-77.89701 33.7868, -77.8952 33....

# What if I need it with my other metadata?
fipio::fips_metadata(fip, geometry = TRUE)
#>   state_region state_division feature_code     state_name state_abbr
#> 1            3              5      1026329 North Carolina         NC
#>          name fip_class tiger_class combined_area_code metropolitan_area_code
#> 1 New Hanover        H1       G4020                 NA                   <NA>
#>   functional_status land_area water_area                       geometry
#> 1                 A 497937486  353803887 MULTIPOLYGON (((-77.89701 3...
#>   fip_code
#> 1    37129

Vectorized

fipio functions are inherently vectorized, so you can use them with vectors of FIPS codes easily:

fips <- c("37129", "44001", "48115")

fipio::fips_state(fips)
#> [1] "North Carolina" "Rhode Island"   "Texas"

fipio::fips_abbr(fips)
#> [1] "NC" "RI" "TX"

fipio::fips_county(fips)
#> [1] "New Hanover" "Bristol"     "Dawson"

fipio::fips_metadata(fips)
#>   state_region state_division feature_code     state_name state_abbr
#> 1            3              5      1026329 North Carolina         NC
#> 2            1              1      1219777   Rhode Island         RI
#> 3            3              7      1383843          Texas         TX
#>          name fip_class tiger_class combined_area_code metropolitan_area_code
#> 1 New Hanover        H1       G4020                 NA                   <NA>
#> 2     Bristol        H4       G4020                148                   <NA>
#> 3      Dawson        H1       G4020                 NA                   <NA>
#>   functional_status  land_area water_area fip_code
#> 1                 A  497937486  353803887    37129
#> 2                 N   62500772   53359134    44001
#> 3                 A 2331781561    4720730    48115

fipio::fips_geometry(fips)
#> Geometry set for 3 features 
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -102.2085 ymin: 32.52327 xmax: -71.20837 ymax: 41.7762
#> Geodetic CRS:  WGS 84
#> MULTIPOLYGON (((-77.89701 33.7868, -77.8952 33....
#> MULTIPOLYGON (((-71.33097 41.68696, -71.32372 4...
#> MULTIPOLYGON (((-102.2027 32.52327, -102.1201 3...

Reverse Geolocate Coordinates to FIPS

fipio contains the ability to locate the FIPS code(s) for a set of coordinates (in WGS84/EPSG:4326):

# With a single set of coordinates
fipio::coords_to_fips(x = -119.8696, y = 34.4184)
#> [1] "06083"

# Vectorized
fipio::coords_to_fips(
    x = c(-81.4980534549709, -81.1249425046948),
    y = c(36.4314781444978, 36.4911893240597)
)
#> [1] "37009" "37005"

# With a `data.frame` or `matrix`
fipio::coords_to_fips(
    x = data.frame(
        X = c(-81.4980534549709, -81.1249425046948),
        Y = c(36.4314781444978, 36.4911893240597)
    ),
    coords = c("X", "Y")
)
#> [1] "37009" "37005"

# With an `sfg` object
fipio::coords_to_fips(
    x   = sf::st_point(c(-81.4980534549709,
                         36.4314781444978)),
    dim = "XY"
)
#> [1] "37009"

# With an `sf` object
fipio::coords_to_fips(
    x = sf::st_as_sf(
        data.frame(X = c(-81.4980534549709, -81.1249425046948),
                   Y = c(36.4314781444978, 36.4911893240597)),
        coords = c("X", "Y"),
        crs = 4326
    )
)
#> [1] "37009" "37005"

fipio's People

Contributors

mikejohnson51 avatar program-- avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

mikejohnson51

fipio's Issues

incorrect FIPS output when using coords_to_fips() on coordinates in Colorado

Hello,

First of all, thank you for developing this package. It's very helpful!

I believe I may have run into a bug when attempting to use coords_to_fips() to convert pairs of coordinates in Colorado to FIPS codes. Instead of getting the corresponding Colorado FIPS codes as my output, I get either a null value or Virginia FIPS codes (51059 and 51153). I'm attempting to use coords_to_fips() on the following pairs of coordinates: (39.705205, -104.760162) , (38.802568, -104.518953) , (38.824734, -104.704033) , and (38.735846, -104.787681).

I'd appreciate any clarity you can provide on this issue.

Thanks very much!

Documentation Additions

  • Add contributing guidelines
  • Add bug report template
  • Create basic vignette showcasing fipio use-cases

ZCTA/Zip code todos

  • Add unit tests for zip code geometry lookup
  • Fix spatial join errors on ZCTA table (i.e. incorrect FIPS codes

Customize corods_to_fips query by year?

Would it be possible to add the ability to query by year to the coords_to_fips function?
Alternatively, are there build instructions somewhere such that I could download the appropriate year's TIGER/Line Shapefiles to compile my own year-specific function?

Ideally I'd like to map coordinates onto the counties present in 2013, and there have been several chances since then.

Thanks!

fipio in AOI

Hi @program--,

As I am trying to work fipio into AOI, it would be very helpful if you could export .metadata_fips.

Do you have any opposition to this?

Mike

Error when assigning coordinates to five-number FIP code

Hello,

I have been having some difficulty getting the fipio package to work properly for some (but not all of my datasets). I'm trying to take a CSV of coordinates (latitude, longitude) into five-number FIPS codes. I then would split those five number codes into the first two numbers for the state and last three numbers for the county/parish, then converting them to state/county names for automatic county-level map production. In some of the datasets I use, I get this error when running the following code:

fipio::coords_to_fips(x = data.frame(points_longitude[i], points_latitude[i], coords = c("X", "Y")))
[1] Error in order(ret_index) : unimplemented type 'list' in 'orderVector1'

It only happens for some CSV files or dataframes, and it doesn't seem to be a case of illegal characters in the coordinates. If I enter in the coordinates manually, it seems fine with that (usually), but bringing in a CSV downloaded from somewhere else usually (but not always) causes this error to pop up. I've spoken with one of my professors who's very familiar with R, and he couldn't figure out what's going on. The latitude and longitude are converted to vectors or numeric format prior to running this line of code (see below), so I think that sometime during the fipio::coord_to_fips() function, something is converted to a list (and should be converted back to a vector but isn't always the case). Why it only happens sometimes I'm not sure, and I wasn't sure where else to ask this sort of question.

points_longitude <- points$longitude; points_longitude <- as.numeric(points_longitude); points_longitude; points_latitude <- points$latitude; points_latitude <- as.numeric(points_latitude); points_latitude

Any thoughts on how to alleviate the issue would be greatly appreciated! Files (one works, one doesn't work) are below, along with the rest of the code,
Marisa

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

coordinates.csv
example_coordinates_simple.csv

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

# Code written by Marisa Szubryt 2024/01/07, modified from links below

# https://cran.r-project.org/web/packages/fipio/readme/README.html
# https://rdrr.io/cran/fipio/f/README.md
# https://www.reddit.com/r/Rlanguage/comments/se5w7b/how_to_replace_comma_that_is_not_followed_by_a/ 
# https://search.r-project.org/CRAN/refmans/totalcensus/html/convert_fips_to_names.html 
# https://search.r-project.org/CRAN/refmans/usdata/html/abbr2state.html
# https://stackoverflow.com/questions/13093931/remove-last-word-from-string 
# https://stackoverflow.com/questions/72408598/r-extract-first-two-characters-from-a-column-in-a-dataframe 
# https://stackoverflow.com/questions/18115550/combine-two-or-more-columns-in-a-dataframe-into-a-new-column-with-a-new-name 

# Set working directory and clear environment
setwd("/Users/mbs/Desktop/Heterotheca/Heterotheca-RCode/Coordinate_county_maps")
rm(list=ls()); graphics.off(); gc()

# Load in map-making packages for coordinate to county conversion
install.packages('dyplr')
install.packages('fipio')
install.packages('stringr')
install.packages('totalcensus')
install.packages('usdata')
library(dplyr)
library(fipio)
library(stringr)
library(totalcensus)
library(usdata)

# Read in CSV with coordinates
# The below CSV works
points <- read.csv('example_coordinates_simple.csv'); attach(points); points; names(points)

# The below CSV doesn't work 
# points <- read.csv('coordinates.csv'); attach(points); points; names(points)

# Add in necessary columns
points$fips<-'';points$state_fips<-'';points$county_fips<-'';points$state_name<-'';points$county_name<-''; points$SC_name<-''

# Extract latitude and longitude
points_longitude <- points$longitude; points_longitude <- as.numeric(points_longitude); points_longitude
points_latitude <- points$latitude; points_latitude <- as.numeric(points_latitude); points_latitude

# Add FIPS codes (2 numbers for state, 3 numbers for county)
fips_codes <- c()
for (i in c(1:length(points_longitude))) {
  fips_iteration <- fipio::coords_to_fips(x = data.frame(points_longitude[i], points_latitude[i], coords = c("X", "Y")))
  fips_codes <- c(fips_codes, fips_iteration)}
fips_codes <- fips_codes [!is.na(fips_codes)]; fips_codes
points$fips <- fips_codes; points$fips <- as.character(points$fips); points$fips; points

# Split 5 number FIPS codes into state and county fip codes
points$state_fips<- substr(points$fips,1,2); fips_states <- points$state_fips; fips_states <- as.character(fips_states); fips_states
points$county_fips<- substr(points$fips,3,5); fips_counties <- points$county_fips; fips_counties <- as.character(fips_counties); fips_counties

# Generate state and county names from FIPS codes 
states_names <- convert_fips_to_names(fips_states); states_names
counties_names <- convert_fips_to_names(fips_counties, states=states_names, geo_header='COUNTY'); counties_names

# Add state/county names into dataframe
points$state_name <- states_names; points$county_name <- counties_names; points

# Convert state abbreviations to full name
points$state_name <- abbr2state(points$state_name); points

# Remove the 'County' portion of the counties_names vector
points <- points %>% mutate(county_name=word(county_name, 1, -2)); points

# Convert state and county to lower case
points$state_name <- tolower(points$state_name); points$county_name <- tolower(points$county_name); points

# Convert the state and county names into a format usable by the county-highlighting code
points$SC_name <- paste(points$state_name, ",", points$county_name); points
points$SC_name <- gsub(" , (?! )", ",", points$SC_name, perl=TRUE); points

# Extract out the list of "state,county" to insert into the county-highlighting code
plantCounties <- points$SC_name; plantCounties

# Export the amended dataframe for reference
write.csv(points, "example_coordinates_simple_amended.csv", row.names=FALSE)

###########################################################################

# Code written by Patrick Alexander (2024/01/02), modified by Marisa Szubryt

# Load in map-making packages
install.packages('ggplot2')
install.packages('maps')
install.packages('sf')
install.packages('tidyverse')
library(ggplot2)
library(sf)
library(maps)
library(tidyverse)

# Run code to automatically set up map-making
states <- st_as_sf(maps::map("state", plot = FALSE, fill = TRUE))
counties <- st_as_sf(maps::map("county", plot = FALSE, fill = TRUE))
plantStates <- substring(plantCounties, 1, regexpr(",", plantCounties) - 1) %>% unique()
counties <- counties %>% 
  mutate(state=substring(ID, 1, regexpr(',', ID)-1)) %>%
  filter(state %in% plantStates)
plantStates <- states %>% filter(ID %in% plantStates)
plantCounties <- counties %>% filter(ID %in% plantCounties)
bbox <- st_bbox(plantStates)
zone <- floor(((mean(c(bbox$xmin,bbox$xmax))+180)/6) +1)
projBbox <- st_bbox(st_transform(plantStates, crs = paste('+proj=utm +zone=',zone,' +datum=WGS84', sep='')))

# Can change thickness/color of state/county bounaries and fill color of selected counties
ggplot(NULL) + geom_sf(data=counties, lwd=0.33, color='black', fill='white') +
  geom_sf(data=plantCounties, lwd=0.33, fill='steelblue') +
  geom_sf(data = states, lwd=0.75, color='black', fill='transparent') +
  coord_sf(crs=paste('+proj=utm +zone=',zone,' +datum=WGS84',sep=''),
           xlim=c(projBbox$xmin, projBbox$xmax), ylim=c(projBbox$ymin, projBbox$ymax), expand=TRUE) +
  theme_void()

Uninformative Error Messages

fipio::as_fips(state = "FAKE")                                                                                                                                                            
#> Error in x[is.na(x)] <- y[!is.na(y)] : replacement has length zero

When as_fips() can't find any data, an error should be returned, but it should be informative.

FIPS Reverse Lookup

Provide a function for reverse FIPS identification with state or county information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.