Skip to contents

This article provides examples of how to use EJAM in RStudio, especially how to use more specialized functions to find specific places to analyze, such as EPA-regulated facilities defined in various ways, and how to explore the results in more detail than the web app can provide.

Running a Basic Analysis

  • ejamapp() launches the web app locally (to run in RStudio on a single computer rather than on a server)

  • ejamit() provides most results in just one function (if you already have a list of places to analyze), as shown in the Basics - Quick Start Guide

Tools for Exploring Results

For a standard analysis, the basic tools like ejam2report(), ejam2excel(), ejam2map(), etc. let you explore results, as shown in the Basics - Quick Start Guide.

If you want more ways to visualize and dig into results, examples are provided below in the sections on EXPLORING RESULTS and VISUALIZATION OF FINDINGS (PLOTS). For example, you can check which groups or which facilities have notable findings.

Tools for Selecting Locations to Analyze

EJAM offers a variety of ways to specify the places to be analyzed and compared. The web app helps you select locations in several ways, including uploading a table of points, selecting facilities by industry category or ID, uploading shapefiles or lists of FIPS codes, and clicking on a map to specify one or more points.

If you are working in RStudio, and you already have identified the points or areas to analyze, the ejamit() function will accept 1) point coordinates, 2) a shapefile, or 3) a list of FIPS codes.

However, if you first need to get the points (lat, lon values), or you need a more in-depth, custom approach to finding facilities or Census places to analyze, there are several groups of functions to help with that, as shown in all the examples below. They are also shown in the EJAM package reference manual, by category.

You can specify locations for analysis in a variety of ways:

Near each point: Analyze residents & the area NEAR EACH POINT (PROXIMITY ANALYSIS)

Within each polygon: Specify areas of any size and shape to analyze residents within each polygon/zone/area (based on shapefiles or Census FIPS codes)

  • within areas or zones on a map if you have GIS data in SHAPEFILES - Polygons (from shapefiles) could for example define redlining zones, higher risk areas based on modeling, etc.

  • within Census units like cities or Counties defined using FIPS CODES - Census Units such as Counties or other types of Census Units are defined by FIPS code (e.g., Counties in one State).

ZIP codes can also be analyzed as ZCTA polygons; see the article on zipcodes.

NEAR EACH POINT (PROXIMITY ANALYSIS)

Latitude and Longitude

You can define locations as all residents within X miles of any one or more of the specified points, and you can define those points in a few ways. One way is to upload a table of coordinates – latitude and longitude for each point, one row per site, with columns called lat and lon (or some synonyms that work). In the web app you can also pick points without a file by choosing “Click or draw on map” and clicking the map to add one or more points (click a point’s marker again to remove it).

There are also more detailed functions for working with latlon coordinates.

The simplest way to do that in the RStudio console is something like x <- ejamit(), which prompts you to upload a spreadsheet with lat lon columns, and asks you for the radius.

As explained below, you can get the latitudes and longitudes of EPA-regulated facilities if you want to specify a set of facilities by uploading their Registry ID numbers in a table, or using other identifiers. For example, there is a function latlon_from_programid() in the examples below.

You can also get coordinates in a few other ways, such as by NAICS (or SIC) industry names or codes, EPA program covering the set of facilities (e.g., all greenhouse gas reporters), or a Clean Air Act MACT subpart.

Facilities by ID

EPA-regulated facilities can be found in the Facility Registry Services by identification number.

See a list of functions related to EPA IDs

by Facility, using EPA Registry ID

# note frs_from_regid() and latlon_from_regid() require the frs dataset, which they try to load on demand.

frs_from_regid(testinput_registry_id[1:2])
frs_from_regid(testinput_regid)

## upload file with table of REGISTRY_ID values
testdata("regi", quiet = T) # to see sample files available with package
x1 <- latlon_from_regid(
  read_csv_or_xl(testdata("testinput_registry_id_8.xlsx", quiet = TRUE))$REGISTRY_ID
  )

## interactively upload your own file with table of REGISTRY_ID values
## (must specify the right column name)
x2 <- latlon_from_regid(read_csv_or_xl()$REGISTRY_ID)

## and run regids through EJAM
y <- ejamit(x1, radius = 1)

by Facility, using EPA Program System ID

# latlon_from_programid() requires access to the frs_by_programid dataset, which it tries to load on demand if necessary.

if (exists("frs_by_programid")) {
  latlon_from_programid(
    testinput_program_sys_id$program[1:2],
    testinput_program_sys_id$pgm_sys_id[1:2]
  )
}
#> Key: <pgm_sys_id, program, REGISTRY_ID>
#>         lat        lon  REGISTRY_ID        PGM_SYS_ACRNMS  program   pgm_sys_id
#>       <num>      <num>       <char>                <char>   <char>       <char>
#> 1: 42.89709  -71.46442 110071943048       NPDES:01R10I002    NPDES    01R10I002
#> 2: 60.53939 -145.74107 110006863153 RCRAINFO:AK0000000323 RCRAINFO AK0000000323

Facilities by Type

See a list of functions related to type of facility (NAICS/SIC/Program/MACT)

by Industry (NAICS)

You can specify sites by NAICS, but it is important to note the FRS lacks NAICS info for many regulated facilities!

naics_from_any("paint and coating", children = T) 
#>      code     n2     n3     n4     n5     n6                            name
#>     <num> <char> <char> <char> <char> <char>                          <char>
#> 1:  32551     32    325   3255  32551  32551 Paint and Coating Manufacturing
#> 2: 325510     32    325   3255  32551 325510 Paint and Coating Manufacturing
#> 3: 325510     32    325   3255  32551 325510 Paint and Coating Manufacturing
#>                                    num_name
#>                                      <char>
#> 1:  32551 - Paint and Coating Manufacturing
#> 2: 325510 - Paint and Coating Manufacturing
#> 3: 325510 - Paint and Coating Manufacturing
## note latlon_from_naics() requires the frs_by_naics dataset, which it tries to load on demand. 
# head(latlon_from_naics(325510)) 
# has about 1,000 facilities  
#
# All sectors with this phrase in their NAICS title
# 
#  x <- ejamit(frs_from_naics("paint and coating"), 1)}

See many more examples of Working with NAICS Codes (Industry Codes), in a section below.

Functions related to NAICS/SIC codes

by EPA Regulatory Program

See a list of functions related to EPA programs

# note latlon_from_programid() requires the frs and frs_by_programid datasets, which it tries to load on demand.
if (exists("frs_by_programid") && exists("frs")) {
  
  ## Map of over 10,000 facilities in FRS identified as in the E-Grid power plant database
  
  pts <- latlon_from_program("EGRID")[, 1:4]
  mapfast(pts)
  
  ## In just 1 State
  pts[, ST := state_from_latlon(lat = lat, lon = lon)$ST]
  mapfast(pts[ST == "TX", ], radius = 1)
  
  ## Largest lists
  
  epa_programs_counts <- frs_by_programid[, .N, by = "program"][order(N), ]
  epa_programs_counts[order(-N), ][1:25, ]
}
#>           program      N
#>            <char>  <int>
#>  1:      RCRAINFO 823117
#>  2:         NPDES 471051
#>  3:      NJ-NJEMS 243102
#>  4: CA-ENVIROVIEW 203747
#>  5:          ICIS 167327
#>  6:      MN-TEMPO 149471
#>  7:           AIR 134144
#>  8:           EIS 124208
#>  9:           FIS 122104
#> 10:   TX-TCEQ ACR 107572
#> 11:      AIRS/AFS  95250
#> 12:      OSHA-OIS  83729
#> 13:          SFDW  70602
#> 14:          NCDB  70163
#> 15:          ACES  63593
#> 16:       WA-FSIS  51448
#> 17:      IDNR_EFD  45827
#> 18:         ACRES  42793
#> 19:        OR-DEQ  42489
#> 20:      IN-TEMPO  39495
#> 21:          TRIS  35420
#> 22:       AZURITE  34862
#> 23:      MA-EPICS  33970
#> 24:       OH-CORE  33809
#> 25:       CA-CERS  31962
#>           program      N
#>            <char>  <int>

by MACT Subpart (hazardous air pollutant source category)

Functions related to MACT codes

# note latlon_from_mactsubpart() requires the frs_by_mact dataset, which it tries to load on demand
if (exists("frs_by_mact")) {
  
  # Search by name of category
  mact_table[grepl("ethylene", mact_table$title, ignore.case = T), ]
  eto <- rbind(
    latlon_from_mactsubpart("O" ), 
    latlon_from_mactsubpart("WWWWW")
  )
  #  Map the category
  mapfast(eto)
  
  
  # Browse the full list of categories
  # mact_table[ , c("N", "subpart", "title")]
  
  # The 10 largest categories
  tail(mact_table[order(mact_table$N), c("N", "subpart", "title")], 10)
  
  # Many facilities lack latitude longitude information in this database
  nrow(latlon_from_mactsubpart("A", include_if_no_latlon = TRUE))
  nrow(latlon_from_mactsubpart("A", include_if_no_latlon = FALSE))
  
  head(latlon_from_mactsubpart("OOOO"), 2)
}
#> Key: <subpart, programid>
#>     programid subpart
#>        <char>  <char>
#> 1: 0500100022    OOOO
#> 2: 06111R9011    OOOO
#>                                                         title
#>                                                        <char>
#> 1: PRINTING, COATING AND DYEING OF FABRICS AND OTHER TEXTILES
#> 2: PRINTING, COATING AND DYEING OF FABRICS AND OTHER TEXTILES
#>                                                       dropdown_label      lat
#>                                                               <char>    <num>
#> 1: OOOO - Printing, Coating And Dyeing Of Fabrics And Other Textiles 34.27496
#> 2: OOOO - Printing, Coating And Dyeing Of Fabrics And Other Textiles 34.22082
#>           lon  REGISTRY_ID      PGM_SYS_ACRNMS  program
#>         <num>       <char>              <char>   <char>
#> 1:  -91.34179 110025082924 AIRS/AFS:0500100022 AIRS/AFS
#> 2: -119.02272 110043415578 AIRS/AFS:06111R9011 AIRS/AFS

Working with NAICS Codes (Industry Codes)

NAICS Codes to Map or Analyze Facilities in one Industrial Sector

Overview of NAICS / industry categories, at n-digit level

# see NAICS categories at the top (2-digit) level

naics_categories()

# see NAICS categories at the 3-digit level

# sorted alphabetical
naics_from_any(naics_categories(3))[order(name),.(name,code)][1:10,]
# sorted by code
naics_from_any(naics_categories(3))[order(code),.(code,name)][1:10,]

Find NAICS codes, from the name of an industry

Find industry names, from the NAICS codes

# get name from one code
naics_from_code(336)$name

# get the name from each code
naics_from_code(mycode)$name

Count facilities by NAICS code

mycode = c(33611, 336111, 336112)

# see counts of facilities by code (parent) and subcategories (children)
naics_counts[NAICS %in% mycode, ]

# see parent codes that contain each code
naicstable[code %in% mycode, ]

Find facilities, by name of industry


# See a data table of facilities in one industry
dataload_dynamic("frs")
#> Loading specified arrow datasets: frs
#> ✅ Token is valid!
#> Arrow-format datasets (blocks, etc.) are up-to-date -- locally-installed and package-compatible data repository versions match.
#> looking for frs in memory...
#> NULL
# if (exists("frs")) {
  industryword <- "pulp"
  
  head( frs_from_naics(naics_from_any(industryword)$code)[,1:4] )
#> Key: <REGISTRY_ID>
#>         lat       lon  REGISTRY_ID                       PRIMARY_NAME
#>       <num>     <num>       <char>                             <char>
#> 1: 42.60008 -72.37838 110000308612                 ERVING PAPER MILLS
#> 2: 42.61366 -71.63378 110000308881               HOLLINGSWORTH & VOSE
#> 3: 42.74216 -73.69249 110000324426       LYDALLTHERMAL/ACOUSTICAL INC
#> 4: 43.97535 -75.90653 110000325988          KNOWLTON TECHNOLOGIES LLC
#> 5: 44.22767 -74.99753 110000326120 NEWTON FALLS LAND RECLAMATION, LLC
#> 6: 41.49085 -78.67752 110000330400   DOMTAR PAPER CO/JOHNSONBURG MILL
# }

Quick map of EPA-regulated facilities in one industrial category, which you can click on to see popup windows about sites.

# note frs_from_naics() requires the frs dataset
# frs_from_naics() is slow the 1st time if it has not yet loaded the frs dataset
if (!exists("frs_arrow")) { # a more efficient format
  dataload_dynamic("frs", return_data_table = FALSE, silent = TRUE)
}

mapfast(frs_from_naics("smelt"))

(but note that this FRS dataset lacks NAICS for most facilities!)

Table of facilities in an industry, plus links to each facility in ECHO and EJSCREEN

industryword <- "chemical manuf"
#  industryword <- "smelt"
# if (exists("frs") && exists("frs_by_naics")) {
  mysites <- frs_from_naics(industryword, children = FALSE)[,1:5]
  
  regids <- mysites$REGISTRY_ID
  link1 <- url_echo_facility(regid = regids, as_html = T)
  link2 <- url_ejamapi(sitepoints = mysites, radius = 3, as_html = T)
  link3 <- url_ejscreenmap(lat = mysites$lat, lon = mysites$lon,  as_html = T)
  # # same:
  # my_industry <- naics_from_any("chemical manuf",children = F)[,.(code,name)]
  # mysites <- frs_from_naics(my_industry$code)[,1:5]
  mysites <- cbind(`ECHO report` = link1, 
                   `EJSCREEN Report` = link2, `EJSCREEN Map` = link3,
                   mysites)
  caption = paste0(nrow(mysites), ' sites have NAICS matching "', industryword, '"')
  if (nrow(mysites) > 1500) {mysites <- mysites[1:1500, ]} # >2k rows is too much for client-side DataTables
  cat(caption,'\n')
  
  print(
    DT::datatable(
      mysites[1:5, ],
      escape = FALSE,     rownames = FALSE,
      caption = caption,
      filter = "top"
    )
  )
# }

Here url_ejamapi() builds links to EJSCREEN-style community reports from the hosted EJAM API, and url_ejscreenmap() builds deep links that open each place on the EJSCREEN map. See the Using the EJAM API article and ?url_ejamapi / ?url_ejscreenmap for the full options (multisite reports, radius, combined links, and the EJSCREEN “Send to EJAM” hand-off).

Map of facilities in an industry, plus popups with links to each facility in ECHO and EJSCREEN

mapfast(mysites)

Facilities searches using industry codes or text in industry names

naics_from_any("plastics and rubber") 
#>     code     n2     n3     n4     n5     n6
#>    <num> <char> <char> <char> <char> <char>
#> 1:   326     32    326    326    326    326
#>                                          name
#>                                        <char>
#> 1: Plastics and Rubber Products Manufacturing
#>                                            num_name
#>                                              <char>
#> 1: 326 - Plastics and Rubber Products Manufacturing

naics_from_any(326)
#>     code     n2     n3     n4     n5     n6
#>    <num> <char> <char> <char> <char> <char>
#> 1:   326     32    326    326    326    326
#>                                          name
#>                                        <char>
#> 1: Plastics and Rubber Products Manufacturing
#>                                            num_name
#>                                              <char>
#> 1: 326 - Plastics and Rubber Products Manufacturing

head(naics_from_any(326, children = T)[,.(code,name)])
#>      code
#>     <num>
#> 1:    326
#> 2:   3261
#> 3:  32611
#> 4: 326111
#> 5: 326112
#> 6: 326113
#>                                                                         name
#>                                                                       <char>
#> 1:                                Plastics and Rubber Products Manufacturing
#> 2:                                            Plastics Product Manufacturing
#> 3: Plastics Packaging Materials and Unlaminated Film and Sheet Manufacturing
#> 4:                                      Plastics Bag and Pouch Manufacturing
#> 5:     Plastics Packaging Film and Sheet (including Laminated) Manufacturing
#> 6:      Unlaminated Plastics Film and Sheet (except Packaging) Manufacturing

naics_from_any("pig") 
#>      code     n2     n3     n4     n5     n6
#>     <num> <char> <char> <char> <char> <char>
#> 1:   1122     11    112   1122   1122   1122
#> 2:  11221     11    112   1122  11221  11221
#> 3: 112210     11    112   1122  11221 112210
#> 4:  32513     32    325   3251  32513  32513
#> 5: 325130     32    325   3251  32513 325130
#>                                       name
#>                                     <char>
#> 1:                     Hog and Pig Farming
#> 2:                     Hog and Pig Farming
#> 3:                     Hog and Pig Farming
#> 4: Synthetic Dye and Pigment Manufacturing
#> 5: Synthetic Dye and Pigment Manufacturing
#>                                            num_name
#>                                              <char>
#> 1:                       1122 - Hog and Pig Farming
#> 2:                      11221 - Hog and Pig Farming
#> 3:                     112210 - Hog and Pig Farming
#> 4:  32513 - Synthetic Dye and Pigment Manufacturing
#> 5: 325130 - Synthetic Dye and Pigment Manufacturing
naics_from_any("pig ") # space after g
#>      code     n2     n3     n4     n5     n6                name
#>     <num> <char> <char> <char> <char> <char>              <char>
#> 1:   1122     11    112   1122   1122   1122 Hog and Pig Farming
#> 2:  11221     11    112   1122  11221  11221 Hog and Pig Farming
#> 3: 112210     11    112   1122  11221 112210 Hog and Pig Farming
#>                        num_name
#>                          <char>
#> 1:   1122 - Hog and Pig Farming
#> 2:  11221 - Hog and Pig Farming
#> 3: 112210 - Hog and Pig Farming

# a OR b,  a AND b,  etc.
a = naics_from_any("plastics")

b = naics_from_any("rubber")

library(data.table)
#> 
#> Attaching package: 'data.table'
#> The following object is masked from 'package:base':
#> 
#>     %notin%
data.table::fintersect(a,b)[,.(name,code)] #  a AND b
#>                                                   name   code
#>                                                 <char>  <num>
#> 1:          Plastics and Rubber Products Manufacturing    326
#> 2: Rubber and Plastics Hoses and Belting Manufacturing  32622
#> 3: Rubber and Plastics Hoses and Belting Manufacturing 326220

head(data.table::funion(a,b)[,.(name,code)])     #  a OR  b
#>                                                                         name
#>                                                                       <char>
#> 1:                                 Plastics Material and Resin Manufacturing
#> 2:                                Plastics and Rubber Products Manufacturing
#> 3:                                            Plastics Product Manufacturing
#> 4: Plastics Packaging Materials and Unlaminated Film and Sheet Manufacturing
#> 5:                                      Plastics Bag and Pouch Manufacturing
#> 6:     Plastics Packaging Film and Sheet (including Laminated) Manufacturing
#>      code
#>     <num>
#> 1: 325211
#> 2:    326
#> 3:   3261
#> 4:  32611
#> 5: 326111
#> 6: 326112

# naics_subcodes_from_code(funion(a,b)[,code])[,.(name,code)]   #  plus children

head(naics_from_any(funion(a,b)[,code], children = T)[,.(name,code)] ) #  same
#>                                                                         name
#>                                                                       <char>
#> 1:                                Plastics and Rubber Products Manufacturing
#> 2:                                            Plastics Product Manufacturing
#> 3: Plastics Packaging Materials and Unlaminated Film and Sheet Manufacturing
#> 4:                                      Plastics Bag and Pouch Manufacturing
#> 5:     Plastics Packaging Film and Sheet (including Laminated) Manufacturing
#> 6:      Unlaminated Plastics Film and Sheet (except Packaging) Manufacturing
#>      code
#>     <num>
#> 1:    326
#> 2:   3261
#> 3:  32611
#> 4: 326111
#> 5: 326112
#> 6: 326113

A NAICS code can have many “children” or subcategories under it

dataload_dynamic(c("frs", "frs_by_naics"))
#> Loading specified arrow datasets: frs, frs_by_naics
#> ✅ Token is valid!
#> Arrow-format datasets (blocks, etc.) are up-to-date -- locally-installed and package-compatible data repository versions match.
#> looking for frs, frs_by_naics in memory...
#> NULL
if (exists("frs") & exists("frs_from_naics")) {
  
  NROW(naics_from_any("chem"))
  # about 20
  NROW(naics_from_any("chem", children = T))
  # >100
  NROW(frs_from_naics(naics_from_any("chem")$code))
  # a few thousand
  NROW(frs_from_naics(naics_from_any("chem", children = T)$code))
  # >10,000
}
#> [1] 16846

SHAPEFILES

Polygons in shapefiles as the places to compare

You can upload polygons in a shapefile, and use EJAM to analyze them. See the Shiny app.

See shapefile_from_any() and other shapefile-related functions:

FIPS CODES

Map of blockgroups like an EJSCREEN map

See map_ejscreen_indicator() for a quick EJSCREEN-style map of blockgroups in a County or State, color-coded by one indicator, without running an analysis.

For blockgroups, shapes_from_fips() keeps its existing service default. For overview maps of many blockgroups, myservice_blockgroup = "cartographic" can be much faster: it downloads and caches one small, generalized boundary file per State. Edges and shorelines are simplified, so these polygons can change area, buffer, or point-in-polygon results. Use "tiger" for full boundary detail; its larger files take longer to download and draw, but are also cached. Neither option needs ACS estimates or a Census API key. These options currently apply to blockgroups, not tracts.

Omitting year or using year = NULL selects acs_endyear() for either tigris blockgroup option. For cities/towns/CDPs, it instead predicts the latest TIGER/Line places vintage from an assumed October 14 annual release. Places are areas to analyze and can have newer boundaries than the demographic data overlaid on them. Set an explicit year, such as year = 2024, for a particular vintage. This calendar estimate does not verify publication or rely on the installed tigris default; use an explicit available year if a release is delayed. Newer boundaries can change city analysis results even before demographic data are updated. If a requested place has no boundary in the selected vintage, EJAM warns with its FIPS code and the year, and preserves its row with empty geometry. An explicit older year can be used when appropriate; EJAM does not silently substitute another vintage.

The v4 data update must also review/rebuild censusplaces against the selected places vintage, so place-name selection and FIPS validation reflect that release.

Built-in county/state boundaries and service URLs retain their own vintage; these must match the release’s demographic geography when the data are updated. Census blocks retain the vintage of EJAM’s block data (currently Census 2020), rather than automatically taking the ACS end year. The year argument here does not override these datasets or service URLs.

bgfips <- blockgroupstats$bgfips[blockgroupstats$ST == "DE"]
# Fast overview boundaries
shp <- shapes_from_fips(bgfips, myservice_blockgroup = "cartographic",
                        year = acs_endyear())
# Full-detail boundaries
shp_detail <- shapes_from_fips(bgfips, myservice_blockgroup = "tiger",
                               year = acs_endyear())

# Both renderers use the same percentile colors; cb = FALSE retains detail.
map_ejscreen_indicator("pctlowinc", ST = "DE", maptype = "ggplot")
map_ejscreen_indicator("pctlowinc", ST = "DE", cb = FALSE)

mapfast() also uses cartographic boundaries when given blockgroup FIPS codes. When you need detailed edges, map shp_detail with map_shapes_leaflet(), or pass it as shp to map_ejscreen_indicator(). These mapping choices do not change existing analysis defaults.

Counties as the places to compare

You can compare places defined by FIPS code, such as a group of US Counties.

See a list of functions for working with Census FIPS codes.

Map EJ stat for each county in the State:

See mapfastej_counties() for a quick map of the counties in a State, color-coded by one of the EJAM indicators, such as the ratio of low-income population to the State average.

Note this direct approach is useful if you only want a map, but it does not save the full results. You can click on a county to see a popup with a link to the EJAM report for that county.

mapfastej_counties(ST = "DE", colorvarname = "ratio.to.state.avg.pctlowinc")

Compare all Counties in a State, using EJAM indicators


# Get FIPS of each county in Delaware
mystate <- "Delaware"
cfips <- fips_counties_from_statename(mystate)

## You could launch a web browser tab for each of the counties,
##  to see County reports like this:
#
# sapply(url_county_health(fips = cfips), browseURL)

## Analyze EJ stats for each county in the State

x <- ejamit(fips = cfips) # radius not used
DT::datatable(x$results_bysite, escape = F)

ejam2table_tall(x)

t(x$results_bysite[ , c(
  'ejam_uniq_id', 'pop', names_d_subgroups_ratio_to_state_avg), with = F])

mapfastej_counties(x$results_bysite)

cnames <- fips2countyname(x$results_bysite$ejam_uniq_id)
#cnames <- c("Kent County", "New Castle County", "Sussex County")
#cnames <- gsub(" County", "", cnames)

barplot(x$results_bysite$pctlowinc, names.arg = cnames,
        main = paste0('% Low Income by County in ', mystate))

# Another example
mystate <- "Maryland"
vname <- "% low income"
xmd <- ejamit(fips = fips_counties_from_statename(mystate))
ggblanket::gg_col(data = xmd$results_bysite,
                  y = pctlowinc,
                  x = ejam_uniq_id,
                  title = paste0(vname, ' by County in ', mystate),
                  y_title = vname
)

mapfastej_counties(xmd$results_bysite, 'state.pctile.pctlowinc')

EXPLORING RESULTS

See also

Color-coded maps

Pass a percentile column name to ejam2map() to color sites gray, yellow, orange, and red at the 80th, 90th, and 95th percentile cutoffs.

out <- testoutput_ejamit_1000pts_1miles
ejam2map(out, color = "pctile.traffic.score", launch_browser = FALSE)

# Or supply a color vector, here comparing traffic scores to State averages:
ejam2map(out,
         color = EJAM:::ratio2color(out$results_bysite$ratio.to.state.avg.traffic.score),
         launch_browser = FALSE)

The ratio colors are gray below 1.05 times the average, yellow from 1.05 to below 2, orange from 2 to below 3, and red at 3 or above. For percentile color vectors, use EJAM:::pctile2color() or EJAM:::pctile2colorhex() on a percentile column. These color helpers are internal functions, hence the ::: notation.

The most striking findings (e.g., which group is most over-represented?)

See examples above using ejam2report() but also you can check some key findings like this:

out <- testoutput_ejamit_1000pts_1miles 
bysite <- out$results_bysite
bysite <- setDF(copy(bysite))
ratio_benchmarks <- c(1.01, 1.50, 2, 3, 5, 10)
ratiodata <- bysite[, names_d_ratio_to_state_avg]

findings <- count_sites_with_n_high_scores(ratiodata, quiet = TRUE)  # long output to console !

tail(findings$text[findings$text != ""], 1) # the most extreme finding!
#> [1] "At at least 2% of these sites, 1 of the indicators is 5 times the average "

The key facilities (e.g., which has the max of – or has multiple elevated – Summary Indexes?)

out2 <- ejamit(
  sitepoints =  testpoints_100,
  radius = 3.1
)
x <- out2$results_summarized$cols
x <- x[order(x[,1], decreasing = T), ]
head(x, 3)
cat("\n")
x <- x[order(x[,2], decreasing = T), ]
head(x, 3)

More summary findings

dimnames(findings)
#> NULL
findings$text[2]
#> [1] "At at least 91% of these sites, 1 of the indicators is 1.05 times the average "
head(findings$stats[ , , 1], 15)
#>      cut
#> count 1.05   2   5  10
#>     0   89 718 977 995
#>     1  214 153  23   5
#>     2  162  69   0   0
#>     3  112  27   0   0
#>     4   76  17   0   0
#>     5   88  12   0   0
#>     6   84   3   0   0
#>     7   96   1   0   0
#>     8   79   0   0   0
#>     9    0   0   0   0
head(findings$stats[ , 1, ], 21)
#>      stat
#> count count  cum pct cum_pct
#>     0    89 1000   9     100
#>     1   214  911  21      91
#>     2   162  697  16      70
#>     3   112  535  11      54
#>     4    76  423   8      42
#>     5    88  347   9      35
#>     6    84  259   8      26
#>     7    96  175  10      17
#>     8    79   79   8       8
#>     9     0    0   0       0
x = findings$stats[ , 1, ] 
x[x[, "cum_pct"] >= 50 & x[, "cum_pct"] <= 80, ]
#>      stat
#> count count cum pct cum_pct
#>     2   162 697  16      70
#>     3   112 535  11      54
findings$stats[ 1, , ]
#>       stat
#> cut    count  cum pct cum_pct
#>   1.05    89 1000   9     100
#>   2      718 1000  72     100
#>   5      977 1000  98     100
#>   10     995 1000 100     100

Local features and special areas – schools, hospitals, nonattainment areas, etc.

ejamit() also provides special summary statistics related to the group of indicators that count features like schools within each blockgroup, overlaps with specially-designated areas such as nonattainment areas, and lack of critical services like health insurance. See the help for batch.summarize() for details.

The function ejam2areafeatures() is just a convenient way to see the information in ejamit()$results_summarized$flagged_areas created by batch.summarize(), as used by ejamit(), from the indicators in these lists:

  • names_featuresinarea
  • names_flag
  • names_criticalservice
Summary of whether residents at the analyzed locations are more likely to have certain types of features (schools) or special areas (Tribal, nonattainment, etc.)

Table

## out1k <- ejamit(testpoints_1000, radius = 1)
out1k <- testoutput_ejamit_1000pts_1miles
ejam2areafeatures(out1k)
#>                                                    Indicator
#> 1                                                Any schools
#> 2                                      Any places of worship
#> 3                                              Any hospitals
#> 4                                    Overlapping with Tribes
#> 5                           Overlapping with Impaired Waters
#> 6                      Overlapping with Non-Attainment Areas
#> 7           Overlapping with CEJST Disadvantaged Communities
#> 8         Overlapping with EPA IRA Disadvantaged Communities
#> 9                Overlapping with Housing Burden Communities
#> 10                        Overlapping with Food Desert Areas
#> 11                   % Households without Broadband Internet
#> 12                         % People without Health Insurance
#> 13 Overlapping with Transportation Disadvantaged Communities
#>    Percent_of_these_Sites Percent_of_these_People
#> 1                    76.8                    29.4
#> 2                    76.3                    34.8
#> 3                    30.2                     5.4
#> 4                     2.7                     0.2
#> 5                    89.6                    41.3
#> 6                    58.0                    81.1
#> 7                    50.8                    40.5
#> 8                    65.8                    51.4
#> 9                    27.7                    28.0
#> 10                   50.9                    14.4
#> 11                    9.7                     8.2
#> 12                    8.1                     8.9
#> 13                   89.9                    58.6
#>    Percent_of_all_People_Nationwide ratio Percent_of_all_People_Statewide
#> 1                              31.5  0.93                            31.4
#> 2                              38.8  0.90                            30.5
#> 3                               4.6  1.17                             4.0
#> 4                               1.5  0.13                             0.8
#> 5                              57.0  0.72                            50.7
#> 6                              57.1  1.42                            75.9
#> 7                              32.0  1.27                            30.0
#> 8                              42.3  1.22                            40.1
#> 9                              12.4  2.26                            17.4
#> 10                             25.0  0.58                            18.5
#> 11                              8.8  0.93                             7.7
#> 12                              8.4  1.06                             7.3
#> 13                             69.6  0.84                            64.3
#>    ratio_to_state_avg                rname
#> 1                0.94           num_school
#> 2                1.14           num_church
#> 3                1.34         num_hospital
#> 4                0.25         yesno_tribal
#> 5                0.81      yesno_impwaters
#> 6                1.07      yesno_airnonatt
#> 7                1.35       yesno_cejstdis
#> 8                1.28         yesno_iradis
#> 9                1.61    yesno_houseburden
#> 10               0.78     yesno_fooddesert
#> 11               1.07       pctnobroadband
#> 12               1.23 pctnohealthinsurance
#> 13               0.91       yesno_transdis

Plots showing whether residents at the analyzed locations are more likely to have certain types of features or special areas

To view these special ratios, since they are not in the main table ejamit()$results_bysite, you can reformat them for plotting like this:

## out <- ejamit(testpoints_1000, radius = 1)
out <- testoutput_ejamit_1000pts_1miles

## simple barplot on special areas and features like schools:

ejam2barplot_areafeatures(out1k)

Barplot of values of ejam2areafeatures(out1k)$ratio for each of the special areas and features, such as schools, hospitals, etc., titled % of analyzed population that lives in blockgroups with given features or that overlap given area type; y axis label as Ratio of indicator in analyzed locations / in US Overall;  showing ratios at 3x US average as orange (shown for overlapping with housing burden communities here), ratios of >1x but <2x as yellow (several bars like for hospitals), and ratios <=1x as gray.


## note the sitenumber param is not supported for these stats

Site by site detailed results in datatable format in RStudio viewer:

out2 <- testoutput_ejamit_100pts_1miles
DT::datatable(out2$results_bysite[1:5,   ], escape = FALSE, rownames = FALSE)

# To see all 1,000 sites in table:
#DT::datatable(out2$results_bysite[1:1000, ], escape = FALSE, rownames = FALSE)

Overall results for a few key indicators, as raw output in console:

out2 <- testoutput_ejamit_100pts_1miles

names(out2)
#> [1] "results_overall"                     "results_bysite"                     
#> [3] "results_bybg_people"                 "longnames"                          
#> [5] "count_of_blocks_near_multiple_sites" "results_summarized"                 
#> [7] "formatted"                           "sitetype"
cbind(overall = as.list( out2$results_overall[ , ..names_d]))
#>                  overall   
#> Demog.Index      1.70558   
#> Demog.Index.Supp 1.705961  
#> pctlowinc        0.3152486 
#> pctlingiso       0.07321168
#> pctunemployed    0.06477913
#> pctlths          0.1295259 
#> pctunder5        0.0563559 
#> pctover64        0.1507945 
#> pctmin           0.5965375
cbind(overall = as.list( out2$results_overall[ , ..names_d_subgroups]))
#>                 overall    
#> pcthisp         0.260957   
#> pctnhba         0.169189   
#> pctnhaa         0.1099694  
#> pctnhaiana      0.003279064
#> pctnhnhpia      0.002279839
#> pctnhotheralone 0.007664835
#> pctnhmulti      0.04319833 
#> pctnhwa         0.4034625

Overall results for the very long list of all indicators, as raw output in console:

out2 <- testoutput_ejamit_100pts_1miles

head(
  ejam2table_tall(out2)
  , 20)
# head(
#   cbind(as.list(out2$results_overall))
#   , 12)

Just one site, all the indicators

head(
  ejam2table_tall(out2, sitenumber = 1)
  , 20)
See indicators aggregated over all people across all sites
## view output of batch run aggregation ####
out <- testoutput_ejamit_1000pts_1miles 
head(cbind(overall = as.list( out$results_overall)))
#>              overall                                                                           
#> EJAM Report  "<a href="https://ejam.publicenvirodata.org" target="_blank">EJAM Site Report</a>"
#> EJSCREEN Map "https://pedp-ejscreen.azurewebsites.net/index.html"                              
#> ejam_uniq_id NA                                                                                
#> valid        TRUE                                                                              
#> invalid_msg  ""                                                                                
#> pop          8633282

## To see just some subset of indicators, like Environmental only:
cbind(overall = as.list( out$results_overall[ , ..names_e])); cat("\n")
#>                 overall  
#> pm              8.420885 
#> o3              63.35274 
#> no2             10.81867 
#> dpm             0.3342198
#> rsei            4586.717 
#> traffic.score   3962589  
#> pctpre1960      0.4005715
#> proximity.npl   1.287661 
#> proximity.rmp   0.8542784
#> proximity.tsdf  10.8667  
#> ust             8.608081 
#> proximity.npdes 531698.7 
#> drinking        1.66891
cbind(overall = as.list( out$results_overall[ , ..names_d])); cat("\n")
#>                  overall   
#> Demog.Index      1.668131  
#> Demog.Index.Supp 1.671838  
#> pctlowinc        0.3038484 
#> pctlingiso       0.07568046
#> pctunemployed    0.0629355 
#> pctlths          0.1302233 
#> pctunder5        0.05567394
#> pctover64        0.146654  
#> pctmin           0.5911751
cbind(overall = as.list( out$results_overall[ , ..names_d_subgroups])); cat("\n")
#>                 overall    
#> pcthisp         0.3000366  
#> pctnhba         0.1396521  
#> pctnhaa         0.09852093 
#> pctnhaiana      0.002710599
#> pctnhnhpia      0.001707782
#> pctnhotheralone 0.006793868
#> pctnhmulti      0.04175326 
#> pctnhwa         0.4088249
cbind(overall = as.list( out$results_overall[ , ..names_e_pctile])); cat("\n")
#>                        overall
#> pctile.pm              62     
#> pctile.o3              57     
#> pctile.no2             80     
#> pctile.dpm             87     
#> pctile.rsei            85     
#> pctile.traffic.score   88     
#> pctile.pctpre1960      67     
#> pctile.proximity.npl   93     
#> pctile.proximity.rmp   77     
#> pctile.proximity.tsdf  91     
#> pctile.ust             87     
#> pctile.proximity.npdes 99     
#> pctile.drinking        84
cbind(overall = as.list( out$results_overall[ , ..names_d_pctile])); cat("\n")
#>                         overall
#> pctile.Demog.Index      68     
#> pctile.Demog.Index.Supp 58     
#> pctile.pctlowinc        57     
#> pctile.pctlingiso       81     
#> pctile.pctunemployed    68     
#> pctile.pctlths          69     
#> pctile.pctunder5        60     
#> pctile.pctover64        41     
#> pctile.pctmin           70
# cbind(overall = as.list( out$results_overall[ , ..names_ej_pctile])); cat("\n")
See the US or State reference averages and percentiles

These lookup tables hold the benchmark values that site results get compared against (for example in the “Compared to US/State Averages” barplots below).

# US mean plus key percentiles, for environmental and demographic indicators
usastats_query(varnames = names_e)
#>   REGION PCTILE      pm      o3     no2    dpm         rsei traffic.score
#> 1    USA      0  2.8671 37.1791  0.0368 0.0006       0.0000          0.00
#> 2    USA      5  5.6867 53.8504  2.7214 0.0399       1.2864      11195.43
#> 3    USA     50  8.0073 62.4184  7.5656 0.1560     603.3185     814620.19
#> 4    USA     80  8.9732 67.0057 10.7128 0.2721    3122.7408    2703377.01
#> 5    USA     90  9.3889 69.9856 12.4906 0.3663    6945.0842    4437550.98
#> 6    USA     95  9.9812 72.4941 14.2647 0.4731   14175.1736    6414517.69
#> 7    USA     99 11.5078 81.5602 17.7103 0.7426   68185.7941   11203610.55
#> 8    USA    100 14.8401 98.4558 25.2692 2.9793 4512172.0810   30181802.55
#> 9    USA   mean  7.9406 62.6273  7.8467 0.1911    4612.4920    1687094.36
#>   pctpre1960 proximity.npl proximity.rmp proximity.tsdf      ust
#> 1     0.0000        0.0000        0.0000         0.0000   0.0000
#> 2     0.0000        0.0000        0.0000         0.0000   0.0000
#> 3     0.2029        0.0000        0.2693         1.2737   0.8245
#> 4     0.5788        0.3791        0.9613         5.2018   5.1739
#> 5     0.7528        0.8415        1.5362         9.4658  10.2870
#> 6     0.8526        1.5986        2.1132        16.0844  17.0191
#> 7     0.9622        7.6291        3.8024        28.7928  35.7900
#> 8     1.0000       46.0823       18.0597        82.2821 137.8717
#> 9     0.2937        0.3947        0.5703         3.5352   3.6379
#>   proximity.npdes drinking
#> 1    0.000000e+00   0.0000
#> 2    0.000000e+00   0.0000
#> 3    5.053510e+01   0.0000
#> 4    2.303414e+03   1.0000
#> 5    1.351623e+04   4.6400
#> 6    4.072222e+04  10.0000
#> 7    2.374242e+05  32.0000
#> 8    7.709095e+09 899.0000
#> 9    7.019193e+05   2.2151

# US means only, as a tidy 1-column matrix (indicators as rownames)
usastats_means(names_d)
#>                  us.avg
#> Demog.Index      1.3685
#> Demog.Index.Supp 1.6439
#> pctlowinc        0.3000
#> pctlingiso       0.0491
#> pctunemployed    0.0549
#> pctlths          0.1086
#> pctunder5        0.0524
#> pctover64        0.1859
#> pctmin           0.4109

# the same for one state: mean plus key percentiles
statestats_query("MD", varnames = names_e)
#>   REGION PCTILE    pm     o3    no2   dpm      rsei traffic.score pctpre1960
#> 1     MD      0 6.083 55.747  1.374 0.029     0.022          0.00      0.000
#> 2     MD      5 6.647 57.781  3.192 0.075    19.548      45189.41      0.000
#> 3     MD     50 7.297 62.316  7.289 0.218   258.382    1351498.75      0.209
#> 4     MD     80 7.466 64.023  9.247 0.281   667.044    2665707.04      0.638
#> 5     MD     90 7.566 64.934 10.231 0.310   951.123    3083701.81      0.810
#> 6     MD     95 7.619 65.500 12.129 0.320  1279.760    3398964.01      0.904
#> 7     MD     99 7.699 66.761 14.731 0.354  2143.295    4094602.44      1.000
#> 8     MD    100 7.774 68.141 17.136 0.615 49507.599    5150543.37      1.000
#> 9     MD   mean 7.245 62.100  7.270 0.208   432.084    1489436.75      0.313
#>   proximity.npl proximity.rmp proximity.tsdf    ust proximity.npdes drinking
#> 1         0.000         0.000          0.000  0.000           0.000    0.000
#> 2         0.000         0.000          0.000  0.000           0.008    0.000
#> 3         0.103         0.179          3.021  1.007          86.222    0.000
#> 4         0.358         0.897          7.585  3.427       11172.758    0.000
#> 5         0.612         1.735         11.380  5.129      204977.996    0.000
#> 6         0.997         2.455         14.531  6.496      766925.607    0.000
#> 7         2.876         3.174         18.700 10.689     2895564.429    1.000
#> 8        11.243         5.143         28.006 17.463    12715947.245   11.000
#> 9         0.278         0.523          4.434  1.883      137010.635    0.045

# state means as a matrix with indicators as rows and one column per state
# (ST may repeat, e.g. one entry per site)
statestats_means(ST = c("MD", "VA"), varnames = names_e[1:3])
#>          MD      VA
#> pm   7.2447  7.2125
#> o3  62.1001 57.6042
#> no2  7.2701  6.3434

VISUALIZATION OF FINDINGS (PLOTS)

See examples below, and the list of plot-related functions.

Indicators

Barplot showing which indicator is most elevated overall

out <- testoutput_ejamit_1000pts_1miles

ejam2barplot(out,
             varnames = c(names_d_ratio_to_state_avg, names_d_subgroups_ratio_to_state_avg),
             main = "Residential population group percentages at Selected Sites Compared to State Averages")

Barplot of ratios of residential population indicators at selected sites to State averages.  It is a series of bars where some are above a ratio of 1, and one is more than 2 times the State average of supplemental demog. index.

Histogram of indicators distribution over all people across all sites

hist(out$results_bysite$pctile.traffic.score, 10, xlab = "Local traffic scores (expressed as a percentile)", 
     ylab = "count of sites in each bin, out of 1,000 sites", freq = TRUE, 
     main = "Actual distribution of scores nearby, as percentiles, 
     vs flat line = USA overall")
abline(h = nrow(out$results_bysite)/10)

Histogram of distribution of scores nearby, in ten decile bins, as percentiles versus a flat line representing the US overall, an expected count of 100 sites per decile, out of 1,000 sites total.  Bars in the first three deciles (low traffic scores) are above the expected 100 line, meaning these sites have an overrepresentation of sites with low traffic scores compared to the US overall.