Spatial_Chapter

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.4.1 
✔ readr   2.1.3      ✔ forcats 0.5.2 
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
library(foreign)
library(readr)
library(haven)
library(janitor)

Attaching package: 'janitor'

The following objects are masked from 'package:stats':

    chisq.test, fisher.test
library(car)
Loading required package: carData

Attaching package: 'car'

The following object is masked from 'package:dplyr':

    recode

The following object is masked from 'package:purrr':

    some

Downloading CDC PLACES data

places_2022 <- read_csv("PLACES__County_Data__GIS_Friendly_Format___2022_release.csv")
Rows: 3143 Columns: 126
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (65): StateAbbr, StateDesc, CountyName, CountyFIPS, ACCESS2_Crude95CI, A...
dbl (61): TotalPopulation, ACCESS2_CrudePrev, ACCESS2_AdjPrev, ARTHRITIS_Cru...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
places_2022$obesity <- places_2022$OBESITY_CrudePrev
places_2022$high_chol <- places_2022$HIGHCHOL_CrudePrev
places_2022$curr_smk <- places_2022$CSMOKING_CrudePrev
places_2022$high_bp <- places_2022$BPHIGH_CrudePrev
places_2022$uninsured <- places_2022$ACCESS2_CrudePrev
places_2022$diabetes <- places_2022$DIABETES_CrudePrev
places_2022$trfips <- places_2022$TractFIPS
Warning: Unknown or uninitialised column: `TractFIPS`.
places_2022$pop <- places_2022$TotalPopulation
places_2022$ann_chck <- places_2022$CHECKUP_CrudePrev

plcs<-places_2022[, c("diabetes","uninsured","high_bp","curr_smk","high_chol","obesity", "CountyFIPS", "pop", "ann_chck")]

plcs$GEOID <- plcs$CountyFIPS

#save(plcs, file="PLACES.Rdata")
#PLACES tract-level data

Pulling data from 2010 and 2020 Census

library(tidycensus)
library(sf)
Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(pacman)

options(tigris_class = "sf")

# Load variables for 2010 census
V10 <- load_variables(2010, "pl", cache = TRUE)

# Load variables for 2020 census
v20 <- load_variables(2020, "pl", cache = TRUE)

# 2010 Total Population variables = P001001
# 2020 Total Population variables = P1_001N
# 2010 Total Hisp/Latino Population = P002002
# 2020 Total Hisp/Latino Population = P2_002N

# 2010 Total Population for US counties
us_2010 <- get_decennial(geography = "county",
variables =  "P001001",
year = 2010)
Getting data from the 2010 decennial Census
Using Census Summary File 1
# 2020 Total Population for US counties
us_2020 <- get_decennial(geography = "county",
variables = "P1_001N",
year = 2020)
Getting data from the 2020 decennial Census
Using the PL 94-171 Redistricting Data summary file
Note: 2020 decennial Census data use differential privacy, a technique that
introduces errors into data to preserve respondent confidentiality.
ℹ Small counts should be interpreted with caution.
ℹ See https://www.census.gov/library/fact-sheets/2021/protecting-the-confidentiality-of-the-2020-census-redistricting-data.html for additional guidance.
This message is displayed once per session.
# Merge data for 2010 and 2020 using GEOID
us_pop <- inner_join(us_2010,us_2020, by = c("GEOID"))

# Order by GEOID
us_total <- us_pop[order(us_pop$GEOID),]

# Rename variables
us_percentchg <- us_total %>% rename(county_2010 = NAME.x, county_2020 = NAME.y,
variable_2010 = variable.x, variable_2020 = variable.y,
total_2010 = value.x, total_2020 = value.y)

# Calculate percent change from 2010 to 2020
us_percentchg <- mutate(us_percentchg, percent_change = (total_2020 - total_2010) / total_2010)

# Format number as percentage with scales package
#us_percentchg$percent_change <- percent(us_percentchg$percent_change, accuracy=0.01)


# 2010 Hispanic Population for US counties
us_2010_h <- get_decennial(geography = "county",
variables =  "P002002",
year = 2010)
Getting data from the 2010 decennial Census
Using Census Summary File 1
# 2020 Hispanic Population for US counties
us_2020_h <- get_decennial(geography = "county",
variables = "P2_002N",
year = 2020)
Getting data from the 2020 decennial Census
Using the PL 94-171 Redistricting Data summary file
# Merge data for 2010 and 2020 using GEOID
us_pop_h <- inner_join(us_2010_h,us_2020_h, by = c("GEOID"))

# Order by GEOID
us_total_h <- us_pop_h[order(us_pop$GEOID),]

# Rename variables
us_percentchg_h <- us_total_h %>% rename(county_2010 = NAME.x, county_2020 = NAME.y,
variable_2010 = variable.x, variable_2020 = variable.y,
hisp_pop_2010 = value.x, hisp_pop_2020 = value.y)

# Calculate percent change from 2010 to 2020
us_percentchg_h <- mutate(us_percentchg_h, percent_change_h = (hisp_pop_2020 - hisp_pop_2010) / hisp_pop_2010)

Loading ACS data and merging with previous data sources

options(tigris_class = "sf")

cat<- load_variables(year = 2020 , dataset = "acs5",
                              cache = TRUE) #demographic profile tables

cat_c <- cat %>% 
  filter(geography =="county")

dat <- get_acs(geography = "county",
                year = 2020,
                variables = c("B06012_001", "B06012_002", "B06009_001", "B06009_002", "B06009_003", "B06009_004", "B06009_005", "B06009_006", "B07411_001", "B07402_001"),
                output = "wide",
                geometry = TRUE)
Getting data from the 2016-2020 5-year ACS
Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |                                                                      |   1%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |==                                                                    |   4%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |=======================                                               |  34%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |===================================================                   |  74%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |===============================================================       |  91%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================|  99%
  |                                                                            
  |======================================================================| 100%
# I want to include SNAP benefits data but they're not available at county level


dat$prop_pov <- (dat$B06012_002E / dat$B06012_001E) * 100

dat$prop_lths <- (dat$B06009_002E / dat$B06009_001E) * 100

dat$prop_hs <- (dat$B06009_003E / dat$B06009_001E) * 100

dat$prop_sm_col <- (dat$B06009_004E / dat$B06009_001E) * 100

dat$prop_bach <- (dat$B06009_005E / dat$B06009_001E) * 100

dat$prop_grad_dg <- (dat$B06009_006E / dat$B06009_001E) * 100

dat$med_hh_inc <- dat$B07411_001E

dat$med_age <- dat$B07402_001E

# B06012_001 = total estimate pop
# B06012_002 = est pop living under 100% pov
# B06009_001 = tot est pop
# B06009_002 = est pop less than hs
# B06009_003 = est pop hs grad
# B06009_004 = est pop some coll
# B06009_005 = est pop bach deg
# B06009_006 = est pop grad deg
# B07411_001 = est median hh income
# B07402_001 = est median age


dog <- merge(dat, us_percentchg, by = "GEOID")

us_counties <- merge(dog, plcs, by = "GEOID")

data_final <- merge(us_counties, us_percentchg_h, by = "GEOID")

data_final$hisp_prop_20 <- (data_final$hisp_pop_2020/data_final$total_2020) * 100

data_final$hisp_prop_10 <- (data_final$hisp_pop_2010/data_final$total_2010) * 100


data_final$hisp_maj <- if_else(data_final$hisp_prop_20>=50, "hisp_majority", "hisp_non_majority")


tabyl(data_final$hisp_maj)
 data_final$hisp_maj    n    percent
       hisp_majority  101 0.03217585
   hisp_non_majority 3038 0.96782415

Characterizing counties by Hispanic population growth; established, high growth, and other

data_final$hisp_estab <- if_else(data_final$hisp_prop_10 >= 10 & data_final$hisp_prop_20 >= 10, 1,0)

tabyl(data_final$hisp_estab)
 data_final$hisp_estab    n   percent
                     0 2428 0.7734947
                     1  711 0.2265053
data_final$hisp_hg <- if_else(data_final$percent_change_h >= 1,1,0)

tabyl(data_final$hisp_hg)
 data_final$hisp_hg    n   percent
                  0 2419 0.7706276
                  1  720 0.2293724
data_final$hisp_othr <- if_else(data_final$hisp_estab == 0 & data_final$hisp_hg == 0, 1,0)

tabyl(data_final$hisp_othr)
 data_final$hisp_othr    n   percent
                    0 1429 0.4552405
                    1 1710 0.5447595
data_final$hisp_check <- paste(data_final$hisp_estab,data_final$hisp_hg,data_final$hisp_othr)

tabyl(data_final$hisp_check)
 data_final$hisp_check    n      percent
                 0 0 1 1710 0.5447594775
                 0 1 0  718 0.2287352660
                 1 0 0  709 0.2258681109
                 1 1 0    2 0.0006371456
# adding the extra 2 counties to the established group


data_final$hisp_cat <- car::recode(data_final$hisp_check, "'0 0 1' = 'other'; '0 1 0' = 'high growth'; '1 0 0' = 'established'; '1 1 0' = 'established'")

tabyl(data_final$hisp_cat)
 data_final$hisp_cat    n   percent
         established  711 0.2265053
         high growth  718 0.2287353
               other 1710 0.5447595

Food insecurity data

library(readr)
food_acc <- read_csv("C:/Users/maman/OneDrive - University of Texas at San Antonio/MHM Fellowship/2019 Food Access Research Atlas Data/Food Access Research Atlas.csv")
Warning: One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat)
Rows: 72531 Columns: 147
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (113): State, County, MedianFamilyIncome, LAPOP1_10, LAPOP05_10, LAPOP1_...
dbl  (34): CensusTract, Urban, Pop2010, OHU2010, GroupQuartersFlag, NUMGQTRS...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# food_acc is by census tract, might use later

library(readxl)
mg_data <- read_excel("C:/Users/maman/OneDrive - University of Texas at San Antonio/MHM Fellowship/Food Security Data/meal_gap_data_2022.xlsx")

mg_2020 <- mg_data %>% 
  filter(Year == 2020)

# merging food insecurity data with the rest
data_final$FIPS <- substr(data_final$GEOID, 2,5)

data_final1 <- merge(data_final,mg_2020, by = "FIPS")

# having an issue merging these data with the final data

Creating my descriptive table

# subsetting to remove Hawaii and Alaska
data_final <- data_final[-(545:549),] #deleting rows by range

data_final <- data_final[-(68:94),] 


table_data <- data_final %>% st_drop_geometry()

library(gtsummary)
table1 <- table_data %>% 
  select(hisp_cat, percent_change, med_age, uninsured, ann_chck, diabetes, obesity, prop_pov, prop_lths, prop_hs, prop_bach, prop_grad_dg) %>% 
  tbl_summary(
    by = hisp_cat,
    label = list(percent_change ~ "percent population change",
                 med_age ~ "median age",
                 uninsured ~ "uninsured rate",
                 ann_chck ~ "annual check-up rate",
                 diabetes ~ "diabetes rate",
                 obesity ~ "obesity rate",
                 prop_pov ~ "proportion under poverty threshold",
                 prop_lths ~ "proportion with less than hs educ",
                 prop_hs ~ "proportion with hs educ",
                 prop_bach ~ "proportion with bachelor's degree",
                 prop_grad_dg ~ "proportion with grad degree"),
    percent = "column",
    missing = "always",
    missing_text = "Missing"
    
  )

table1
Characteristic established, N = 7081 high growth, N = 7021 other, N = 1,6971
percent population change 0.05 (-0.01, 0.11) -0.05 (-0.09, 0.00) 0.00 (-0.05, 0.05)
    Missing 0 0 0
median age 38.7 (35.9, 41.6) 45.2 (41.8, 49.0) 41.8 (39.4, 44.3)
    Missing 0 2 0
uninsured rate 18.5 (13.8, 25.4) 14.0 (11.7, 18.4) 13.3 (10.9, 17.2)
    Missing 0 0 0
annual check-up rate 72.6 (69.6, 75.9) 75.9 (73.3, 78.0) 76.9 (75.0, 78.6)
    Missing 0 0 0
diabetes rate 12.00 (10.50, 13.80) 13.40 (11.80, 15.17) 12.20 (10.80, 14.20)
    Missing 0 0 0
obesity rate 35.1 (30.9, 37.9) 36.6 (34.1, 39.3) 36.9 (34.0, 39.3)
    Missing 0 0 0
proportion under poverty threshold 13.5 (10.7, 16.6) 13.5 (9.9, 18.9) 13.8 (10.4, 17.8)
    Missing 0 0 0
proportion with less than hs educ 12.9 (9.6, 18.2) 11.4 (7.4, 17.4) 10.4 (7.6, 14.4)
    Missing 0 0 0
proportion with hs educ 30 (25, 34) 36 (31, 41) 35 (31, 40)
    Missing 0 0 0
proportion with bachelor's degree 14.8 (11.6, 20.2) 13.0 (9.4, 16.8) 13.4 (10.4, 17.5)
    Missing 0 0 0
proportion with grad degree 7.5 (5.5, 11.6) 5.4 (4.2, 6.9) 7.0 (5.4, 10.0)
    Missing 0 0 0
1 Median (IQR)
# Still want to include variables for SNAP benefits and food insecurity (ex: prop of the pop living greater than 1 mile from a supermarket)

Making maps showing pop change, obesity rates, and Hispanic growth

library(tmap)
tmap_mode("plot")
tmap mode set to plotting
map_1 <- tm_shape(data_final)+
  tm_polygons(c("percent_change"), title=c("% pop change"), palette="RdBu", breaks=c(-.5, -.25, -.1, -.05, -.01, .01, .05, .1, .25, .5),
               style= "fixed",midpoint= 0, border.alpha = 0)+
  tmap_options(max.categories = 9)+
  tm_format("World", legend.outside=T, title.size =4)+
  tm_layout(main.title="2010-2020 Percentage Population Change by County", title.size =8, bg.color = "grey85", legend.frame = TRUE, title.position = c('right', 'top'))+
  tm_credits("Data source: 2010 and 2020 US Decennial Census", position =c("left","bottom"), size =1)

map_1
Warning: Values have found that are higher than the highest break

map_2<- tm_shape(data_final)+
  tm_polygons(c("obesity"), title=c("Obesity"), palette="Reds", n=5, border.alpha = 0)+
  tm_format("World", legend.outside=T, title.size =5)+
  tm_layout(main.title="County Obesity Rates", title.size =8, legend.width =5, bg.color = "grey85", legend.frame = TRUE, title.position = c('right', 'top'))+
  tm_credits("Data source: CDC PLACES", position =c("left","bottom"), size =0.5)

map_2

map_3 <- tm_shape(data_final)+
  tm_polygons(c("hisp_cat"), title=c("Hispanic Destinations"), palette = "Set3", border.alpha = 0)+
  tm_format("World", legend.outside=T, title.size =5)+
  tm_layout(main.title="Hispanic Destination Category", title.size =8, legend.width =5, bg.color = "grey85", legend.frame = TRUE, title.position = c('right', 'top'))+
  tm_credits("Data source: US Census", position =c("left","bottom"), size =0.5)

map_3

Plotting obesity prevalence with the Hispanic population proportion, then creating a spatial neighbor list

qplot(y = data_final$obesity,
      x=data_final$hisp_prop_20)
Warning: `qplot()` was deprecated in ggplot2 3.4.0.

library(spdep)
Loading required package: sp
Loading required package: spData
To access larger datasets in this package, install the spDataLarge
package with: `install.packages('spDataLarge',
repos='https://nowosad.github.io/drat/', type='source')`
# Queen
queen<-poly2nb(data_final, queen=T)
summary(queen)
Neighbour list object:
Number of regions: 3107 
Number of nonzero links: 18114 
Percentage nonzero weights: 0.1876428 
Average number of links: 5.830061 
3 regions with no links:
1219 1225 2978
Link number distribution:

   0    1    2    3    4    5    6    7    8    9   10   11   13   14 
   3   21   46   86  295  659 1068  657  209   49   11    1    1    1 
21 least connected regions:
1216 1271 1328 1878 2312 2880 2915 2916 2919 2921 2922 2928 2930 2934 2937 2945 2948 2950 2955 2965 3059 with 1 link
1 most connected region:
2793 with 14 links
# K=4 nn
q_list<-nb2listw(neighbours=queen, style="W", zero.policy = TRUE)
knn<-knearneigh(x=coordinates(as(data_final, "Spatial")), k=4)
knn4<-knn2nb(knn=knn)

Plotting k nearest neighbors and calculating global Moran’s I

plot(as(data_final, "Spatial"),
     main="k=4 Neighbors")
plot(knn4,
     coords=coordinates(as(data_final, "Spatial")),
     add=T,
     col=2)

# testing for autocorrelation using Moran's I
moran.test(data_final$obesity, 
           listw=q_list,
           zero.policy = TRUE)

    Moran I test under randomisation

data:  data_final$obesity  
weights: q_list  n reduced by no-neighbour observations
  

Moran I statistic standard deviate = 58.32, p-value < 2.2e-16
alternative hypothesis: greater
sample estimates:
Moran I statistic       Expectation          Variance 
     0.6275177511     -0.0003222688      0.0001158946 
# Moran's I value of 0.62 suggests counties with high obesity rates are clustered around each other.

Calculating local Moran’s I and plotting Local Indicator of Spatial Autocorrelation (LISA) map

locali<-localmoran(data_final$obesity, listw = q_list, zero.policy = TRUE, alternative = "two.sided" )
data_final$locali<-locali[,1]
data_final$localp<-locali[,5]

data_final$sobese<-scale(data_final$obesity)
data_final$lag_obese<-lag.listw(var=data_final$sobese, x = q_list)
Warning in lag.listw(var = data_final$sobese, x = q_list): NAs in lagged values
data_final$quad_sig <- NA
data_final$quad_sig[(data_final$sobese >= 0 & data_final$lag_obese >= 0) & (data_final$localp <= 0.05)] <- "H-H" #high high
data_final$quad_sig[(data_final$sobese <= 0 & data_final$lag_obese <= 0) & (data_final$localp <= 0.05)] <- "L-L" #low low
data_final$quad_sig[(data_final$sobese >= 0 & data_final$lag_obese <= 0) & (data_final$localp <= 0.05)] <- "H-L" #high low
data_final$quad_sig[(data_final$sobese <= 0 & data_final$lag_obese >= 0) & (data_final$localp <= 0.05)] <- "L-H" #low high

#WE ASSIGN A # Set the breaks for the thematic map classes
breaks <- seq(1, 5, 1)

# Set the corresponding labels for the thematic map classes
labels <- c("High-High", "Low-Low", "High-Low", "Low-High", "Not Clustered")

# see ?findInterval - This is necessary for making a map
np <- findInterval(data_final$quad_sig, breaks)
Warning in findInterval(data_final$quad_sig, breaks): NAs introduced by coercion
# Assign colors to each map class
colors <- c("red", "blue", "lightpink", "skyblue2", "white")
lisa_map <-data_final%>%
  ggplot()+
  geom_sf(aes(fill = quad_sig))+
  ggtitle("Moran LISA Cluster Map - Obesity Rates",
          sub="United States")

lisa_map

Spatial Regression