rsconnect::setAccountInfo(name = 'bdq9mo-allison-hallowell',
                          token = 'FB0A0CE55C982B81F3A3AEBBF20F79CD',
                          secret = '9MNvc7Kc0Lf1vAJgxNw7KNQDESazQR34Iwc4T2o1',
                          server = 'posit.cloud')
install.packages("tidyverse")
## 
## The downloaded binary packages are in
##  /var/folders/2l/27g2p3vs4cj8t70v145f6w8w0000gn/T//Rtmp4wTFcM/downloaded_packages
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(readr)
fema_data_2023_2024 <- read_csv("Desktop/LSC/fema_data_2023_2024.csv")
## New names:
## Rows: 1761473 Columns: 72
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (17): incidentType, county, damagedStateAbbreviation, damagedCity, dama... dbl
## (52): ...1, disasterNumber, occupantsUnderTwo, occupants2to5, occupants... lgl
## (1): sbaEligible dttm (1): lastRefresh date (1): declarationDate
## ℹ 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.
## • `` -> `...1`
# Assuming your dataset is already loaded and named fema_data_2023_2024

# Remove "(county)" from the county column
fema_data_2023_2024$county <- gsub("\\(county\\)", "", fema_data_2023_2024$county, ignore.case = TRUE)

# Trim any leading or trailing whitespace
fema_data_2023_2024$county <- trimws(fema_data_2023_2024$county)
# Install required packages if not already installed
if (!requireNamespace("dplyr", quietly = TRUE)) install.packages("dplyr")
if (!requireNamespace("leaflet", quietly = TRUE)) install.packages("leaflet")
if (!requireNamespace("sf", quietly = TRUE)) install.packages("sf")
if (!requireNamespace("maps", quietly = TRUE)) install.packages("maps")
if (!requireNamespace("DT", quietly = TRUE)) install.packages("DT")
if (!requireNamespace("htmltools", quietly = TRUE)) install.packages("htmltools")

# Load required libraries
library(dplyr)
library(leaflet)
library(sf)
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(maps)
## 
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
## 
##     map
library(DT)
library(htmltools)

# Assuming disaster_summary is the dataframe we created earlier
disaster_summary <- fema_data_2023_2024 %>%
  group_by(incidentType, declarationDate, disasterNumber, damagedStateAbbreviation) %>%
  summarise(applications = n(), .groups = 'drop') %>%
  arrange(desc(applications))


# Calculate total applications per state and keep disaster breakdown
state_data <- disaster_summary %>%
  group_by(damagedStateAbbreviation) %>%
  summarise(
    total_applications = sum(applications),
    disaster_breakdown = list(tibble(disasterNumber, declarationDate, applications))
  ) %>%
  ungroup()

# Get US states map data
us_states <- st_as_sf(maps::map("state", plot = FALSE, fill = TRUE))
us_states$name <- tolower(us_states$ID)

# Create a data frame with state names and abbreviations
state_info <- data.frame(
  name = tolower(state.name),
  abbreviation = state.abb
)

# Join the state info and application data with the map data
us_states <- us_states %>%
  left_join(state_info, by = "name") %>%
  left_join(state_data, by = c("abbreviation" = "damagedStateAbbreviation"))

# Replace NA counts with 0 and empty list
us_states$total_applications[is.na(us_states$total_applications)] <- 0
us_states$disaster_breakdown[is.na(us_states$disaster_breakdown)] <- list(tibble(disasterNumber = character(), declarationDate = as.Date(character()), applications = numeric()))

# Create logarithmic color palette
max_applications <- max(us_states$total_applications, na.rm = TRUE)
log_breaks <- c(1, 10, 100, 1000, 10000, 100000, 1000000, max_applications)
pal <- colorBin(
  palette = "YlOrRd",
  domain = us_states$total_applications,
  bins = log_breaks,
  na.color = "white"
)

# Function to create popup content
create_popup_content <- function(state, total, breakdown) {
  if (is.null(breakdown) || nrow(breakdown) == 0) {
    return(paste0("<strong>", state, "</strong><br>No application data available"))
  }
  
  breakdown_table <- breakdown %>%
    arrange(desc(applications)) %>%
    slice_head(n = 10) %>%  # Show top 10 disasters
    mutate(
      applications = format(applications, big.mark = ","),
      declarationDate = format(declarationDate, "%Y-%m-%d"),
      disasterNumber = sprintf('<span style="float:left;">%s</span>', disasterNumber)
    ) %>%
    knitr::kable(format = "html", col.names = c("Disaster Number", "Declaration Date", "Applications"), escape = FALSE)
  
  paste0(
    "<strong>", state, "</strong><br>",
    "Total Applications: ", format(total, big.mark = ","), "<br><br>",
    breakdown_table
  )
}

# Create the map
m <- leaflet(us_states) %>%
  addTiles() %>%
  setView(lng = -98, lat = 39, zoom = 4) %>%
  addPolygons(
    fillColor = ~pal(total_applications),
    weight = 2,
    opacity = 1,
    color = "black",
    dashArray = "3",
    fillOpacity = 0.7,
    highlightOptions = highlightOptions(
      weight = 5,
      color = "#666",
      dashArray = "",
      fillOpacity = 0.7,
      bringToFront = TRUE
    ),
    popup = ~lapply(seq_len(nrow(us_states)), function(i) {
      create_popup_content(us_states$abbreviation[i], us_states$total_applications[i], us_states$disaster_breakdown[[i]])
    }),
    label = ~paste0(
      abbreviation, ": ", 
      format(total_applications, big.mark = ","), " applications"
    ),
    labelOptions = labelOptions(
      style = list("font-weight" = "normal", padding = "3px 8px"),
      textsize = "15px",
      direction = "auto"
    )
  ) %>%
  addLegend(
    pal = pal,
    values = ~total_applications,
    opacity = 0.7,
    title = "Total Applications",
    position = "bottomright",
    labFormat = labelFormat(big.mark = ",", digits = 0)
  )
## Warning: sf layer has inconsistent datum (+proj=longlat +ellps=clrk66 +no_defs).
## Need '+proj=longlat +datum=WGS84'
## Warning in pal(total_applications): Some values were outside the color scale
## and will be treated as NA
# Create a data table for total applications per disaster number, including declaration date
disaster_table <- disaster_summary %>%
  group_by(disasterNumber, declarationDate) %>%
  summarise(total_applications = sum(applications), .groups = "drop") %>%
  arrange(desc(total_applications))

dt <- datatable(
  disaster_table,
  options = list(pageLength = 10, scrollY = "300px"),
  rownames = FALSE,
  colnames = c("Disaster Number", "Declaration Date", "Total Applications")
) %>%
  formatDate("declarationDate", method = "toLocaleDateString")

# Combine map and table in a single output
output <- tagList(
  tags$h2("FEMA Data Visualization"),
  tags$div(style = "display: flex; flex-direction: column; height: 800px;",
    tags$div(style = "flex: 2;", m),
    tags$div(style = "flex: 1; overflow-y: auto;",
      tags$h3("Total Applications per Disaster Number"),
      dt
    )
  )
)

# Display the combined output
output

FEMA Data Visualization

Total Applications per Disaster Number

# Install required packages if not already installed
if (!requireNamespace("dplyr", quietly = TRUE)) install.packages("dplyr")
if (!requireNamespace("leaflet", quietly = TRUE)) install.packages("leaflet")
if (!requireNamespace("sf", quietly = TRUE)) install.packages("sf")
if (!requireNamespace("tigris", quietly = TRUE)) install.packages("tigris")
if (!requireNamespace("htmltools", quietly = TRUE)) install.packages("htmltools")

# Load required libraries
library(dplyr)
library(leaflet)
library(sf)
library(tigris)
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
library(htmltools)

# Assuming fema_data_2023_2024 is your original dataset
# Summarize data by county
county_summary <- fema_data_2023_2024 %>%
  group_by(county, damagedStateAbbreviation, incidentType, declarationDate, disasterNumber) %>%
  summarise(applications = n(), .groups = 'drop') %>%
  arrange(desc(applications))

# Calculate total applications per county and keep disaster breakdown
county_data <- county_summary %>%
  group_by(county, damagedStateAbbreviation) %>%
  summarise(
    total_applications = sum(applications),
    disaster_breakdown = list(tibble(disasterNumber, declarationDate, incidentType, applications))
  ) %>%
  ungroup()
## `summarise()` has grouped output by 'county'. You can override using the
## `.groups` argument.
# Get US counties map data
us_counties <- counties(cb = TRUE, resolution = "20m")
## Retrieving data for the year 2022
##   |                                                                              |                                                                      |   0%  |                                                                              |=                                                                     |   2%  |                                                                              |====                                                                  |   5%  |                                                                              |=====                                                                 |   7%  |                                                                              |======                                                                |   9%  |                                                                              |========                                                              |  11%  |                                                                              |==========                                                            |  14%  |                                                                              |===========                                                           |  16%  |                                                                              |=============                                                         |  18%  |                                                                              |==============                                                        |  20%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  23%  |                                                                              |==================                                                    |  25%  |                                                                              |===================                                                   |  27%  |                                                                              |====================                                                  |  28%  |                                                                              |=====================                                                 |  30%  |                                                                              |======================                                                |  32%  |                                                                              |========================                                              |  34%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |============================                                          |  39%  |                                                                              |=============================                                         |  41%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  45%  |                                                                              |=================================                                     |  47%  |                                                                              |==================================                                    |  48%  |                                                                              |===================================                                   |  50%  |                                                                              |====================================                                  |  52%  |                                                                              |======================================                                |  54%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  57%  |                                                                              |=========================================                             |  59%  |                                                                              |===========================================                           |  61%  |                                                                              |============================================                          |  63%  |                                                                              |=============================================                         |  64%  |                                                                              |==============================================                        |  66%  |                                                                              |================================================                      |  68%  |                                                                              |=================================================                     |  70%  |                                                                              |==================================================                    |  72%  |                                                                              |===================================================                   |  73%  |                                                                              |=====================================================                 |  75%  |                                                                              |======================================================                |  77%  |                                                                              |=======================================================               |  79%  |                                                                              |========================================================              |  81%  |                                                                              |==========================================================            |  82%  |                                                                              |===========================================================           |  84%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  88%  |                                                                              |===============================================================       |  89%  |                                                                              |================================================================      |  91%  |                                                                              |=================================================================     |  93%  |                                                                              |==================================================================    |  95%  |                                                                              |====================================================================  |  97%  |                                                                              |===================================================================== |  99%  |                                                                              |======================================================================| 100%
# Join the county application data with the map data
us_counties <- us_counties %>%
  left_join(county_data, by = c("NAME" = "county", "STUSPS" = "damagedStateAbbreviation"))

# Replace NA counts with 0 and empty list
us_counties$total_applications[is.na(us_counties$total_applications)] <- 0
us_counties$disaster_breakdown[is.na(us_counties$disaster_breakdown)] <- list(tibble(disasterNumber = character(), declarationDate = as.Date(character()), incidentType = character(), applications = numeric()))

# Create logarithmic color palette
max_applications <- max(us_counties$total_applications, na.rm = TRUE)
log_breaks <- c(1, 10, 100, 1000, 10000, 100000, max_applications)
pal <- colorBin(
  palette = "YlOrRd",
  domain = us_counties$total_applications,
  bins = log_breaks,
  na.color = "white"
)

# Function to create popup content
create_popup_content <- function(county, state, total, breakdown) {
  if (is.null(breakdown) || nrow(breakdown) == 0) {
    return(paste0("<strong>", county, ", ", state, "</strong><br>No application data available"))
  }
  
  breakdown_table <- breakdown %>%
    arrange(desc(applications)) %>%
    slice_head(n = 5) %>%  # Show top 5 disasters
    mutate(
      applications = format(applications, big.mark = ","),
      declarationDate = format(declarationDate, "%Y-%m-%d"),
      disasterNumber = sprintf('<span style="float:left;">%s</span>', disasterNumber)
    ) %>%
    knitr::kable(format = "html", col.names = c("Disaster Number", "Declaration Date", "Incident Type", "Applications"), escape = FALSE)
  
  paste0(
    "<strong>", county, ", ", state, "</strong><br>",
    "Total Applications: ", format(total, big.mark = ","), "<br><br>",
    breakdown_table
  )
}

# Create the map
m <- leaflet(us_counties) %>%
  addTiles() %>%
  setView(lng = -98, lat = 39, zoom = 4) %>%
  addPolygons(
    fillColor = ~pal(total_applications),
    weight = 1,
    opacity = 1,
    color = "white",
    dashArray = "3",
    fillOpacity = 0.7,
    highlightOptions = highlightOptions(
      weight = 5,
      color = "#666",
      dashArray = "",
      fillOpacity = 0.7,
      bringToFront = TRUE
    ),
    popup = ~lapply(seq_len(nrow(us_counties)), function(i) {
      create_popup_content(us_counties$NAME[i], us_counties$STUSPS[i], us_counties$total_applications[i], us_counties$disaster_breakdown[[i]])
    }),
    label = ~paste0(
      NAME, ", ", STUSPS, ": ",
      format(total_applications, big.mark = ","), " applications"
    ),
    labelOptions = labelOptions(
      style = list("font-weight" = "normal", padding = "3px 8px"),
      textsize = "12px",
      direction = "auto"
    )
  ) %>%
  addLegend(
    pal = pal,
    values = ~total_applications,
    opacity = 0.7,
    title = "Total Applications",
    position = "bottomright",
    labFormat = labelFormat(big.mark = ",", digits = 0)
  )
## Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
## Need '+proj=longlat +datum=WGS84'
## Warning in pal(total_applications): Some values were outside the color scale
## and will be treated as NA
# Display the map
m
# Load required libraries
library(httr)
library(jsonlite)
## 
## Attaching package: 'jsonlite'
## The following object is masked from 'package:purrr':
## 
##     flatten
library(dplyr)
library(lubridate)
library(ggplot2)
library(maps)
library(scales)  # For pretty_breaks function
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
# Function to fetch data from the API
fetch_fema_data <- function(url, declarationDate, limit = 1000, offset = 0) {
  query_params <- list(
    "$filter" = paste0("declarationDate ge '", declarationDate, 
                       "' and (disasterNumber le 1999 or (disasterNumber ge 4000 and disasterNumber le 4999))"),
    "$orderby" = "declarationDate desc",
    "$top" = limit,
    "$skip" = offset
  )
  
  response <- GET(url, query = query_params)
  
  if (status_code(response) != 200) {
    stop("Failed to fetch data from the API. Status code: ", status_code(response))
  }
  
  content <- content(response, "text", encoding = "UTF-8")
  data <- fromJSON(content)
  
  return(data$DisasterDeclarationsSummaries)
}

# Main script
main <- function() {
  base_url <- "https://www.fema.gov/api/open/v2/DisasterDeclarationsSummaries"
  all_data <- data.frame()
  
  start_date <- "2023-01-01"
  chunk_size <- 1000
  
  cat("Fetching data from FEMA API...\n")
  
  offset <- 0
  repeat {
    cat(sprintf("Fetching records starting from offset %d\n", offset))
    chunk <- fetch_fema_data(base_url, start_date, chunk_size, offset)
    all_data <- bind_rows(all_data, chunk)
    
    if (nrow(chunk) < chunk_size) break
    offset <- offset + chunk_size
  }
  
  cat(sprintf("Total records fetched: %d\n", nrow(all_data)))
  
  # Convert declarationDate to Date type and disasterNumber to numeric
  all_data$declarationDate <- as.Date(all_data$declarationDate)
  all_data$disasterNumber <- as.numeric(all_data$disasterNumber)
  
  # Keep only unique disaster declarations
  filtered_data <- all_data %>%
    distinct(disasterNumber, .keep_all = TRUE)
  
  cat(sprintf("\nUnique major disaster declarations from %s to %s: %d\n", 
              start_date, format(Sys.Date(), "%Y-%m-%d"), nrow(filtered_data)))
  
  # Analyze incident types
  incident_types <- filtered_data %>%
    group_by(incidentType) %>%
    summarise(count = n()) %>%
    arrange(desc(count))
  
  cat("\nIncident types for major disasters from 2023-01-01 onwards:\n")
  print(incident_types)
  
  # Count disasters by state
  state_counts <- filtered_data %>%
    group_by(state) %>%
    summarise(count = n()) %>%
    arrange(desc(count))
  
  # Get US state map data
  us_states <- map_data("state")
  
  # Convert state abbreviations to full names for joining
  state_counts$region <- tolower(state.name[match(state_counts$state, state.abb)])
  
  # Join map data with disaster counts
  map_data <- left_join(us_states, state_counts, by = "region")
  
  # Create the map
  p <- ggplot(data = map_data, aes(x = long, y = lat, group = group, fill = count)) +
    geom_polygon(color = "white") +
    scale_fill_gradient(name = "Number of\nMajor Disasters",
                        low = "lightblue", high = "darkblue",
                        na.value = "grey90",
                        breaks = pretty_breaks(n = 5),  # Use pretty breaks for whole numbers
                        labels = function(x) sprintf("%d", x)) +  # Format labels as integers
    coord_fixed(1.3) +
    theme_minimal() +
    labs(title = "FEMA Major Disaster Declarations by State (2023-01-01 onwards)",
         subtitle = paste("Total declarations:", sum(state_counts$count, na.rm = TRUE)),
         caption = "Data source: FEMA Disaster Declarations Summaries") +
    theme(axis.title.x = element_blank(),
          axis.text.x = element_blank(),
          axis.ticks.x = element_blank(),
          axis.title.y = element_blank(),
          axis.text.y = element_blank(),
          axis.ticks.y = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank())
  
  # Display the map
  print(p)
  
  cat("Map has been displayed in R\n")
  
  # Display summary of state counts
  cat("\nStates by number of major disaster declarations (2023-01-01 onwards):\n")
  print(state_counts)
  
  # Additional analysis: Average number of days between incident begin and declaration
  filtered_data$incidentBeginDate <- as.Date(filtered_data$incidentBeginDate)
  avg_days_to_declaration <- filtered_data %>%
    mutate(days_to_declaration = as.numeric(declarationDate - incidentBeginDate)) %>%
    summarise(avg_days = mean(days_to_declaration, na.rm = TRUE))
  
  cat(sprintf("\nAverage number of days between incident begin and declaration: %.2f\n", avg_days_to_declaration$avg_days))
  
  # ... (previous code remains the same)

# List of disaster declarations
cat("\nList of major disaster declarations from 2023-01-01 onwards:\n")
disaster_list <- filtered_data %>%
  select(disasterNumber, declarationDate, state, incidentType, declarationTitle) %>%
  arrange(desc(declarationDate))

# Modified print statement
print(disaster_list, n = nrow(disaster_list), na.print = "NA")

}

# Run the main function
main()
## Fetching data from FEMA API...
## Fetching records starting from offset 0
## Fetching records starting from offset 1000
## Total records fetched: 1592
## 
## Unique major disaster declarations from 2023-01-01 to 2024-08-28: 132
## 
## Incident types for major disasters from 2023-01-01 onwards:
## # A tibble: 11 × 2
##    incidentType        count
##    <chr>               <int>
##  1 Severe Storm           63
##  2 Flood                  34
##  3 Winter Storm           11
##  4 Hurricane               6
##  5 Tornado                 5
##  6 Fire                    3
##  7 Mud/Landslide           3
##  8 Tropical Storm          3
##  9 Snowstorm               2
## 10 Earthquake              1
## 11 Straight-Line Winds     1

## Map has been displayed in R
## 
## States by number of major disaster declarations (2023-01-01 onwards):
## # A tibble: 44 × 3
##    state count region       
##    <chr> <int> <chr>        
##  1 CA       13 california   
##  2 TN        8 tennessee    
##  3 ME        7 maine        
##  4 NH        6 new hampshire
##  5 OK        6 oklahoma     
##  6 VT        6 vermont      
##  7 SD        5 south dakota 
##  8 AR        4 arkansas     
##  9 FL        4 florida      
## 10 IA        4 iowa         
## # ℹ 34 more rows
## 
## Average number of days between incident begin and declaration: 64.49
## 
## List of major disaster declarations from 2023-01-01 onwards:
##     disasterNumber declarationDate state        incidentType
## 1             4813      2024-08-23    MT Straight-Line Winds
## 2             4808      2024-08-20    NE        Severe Storm
## 3             4812      2024-08-20    NH        Severe Storm
## 4             4811      2024-08-20    KS        Severe Storm
## 5             4810      2024-08-20    VT        Severe Storm
## 6             4809      2024-08-20    NM               Flood
## 7             4807      2024-08-15    SD               Flood
## 8             4806      2024-08-10    FL      Tropical Storm
## 9             4804      2024-07-23    KY        Severe Storm
## 10            4803      2024-07-23    MO        Severe Storm
## 11            4802      2024-07-23    OK        Severe Storm
## 12            4805      2024-07-23    PR               Flood
## 13            4801      2024-07-18    MT        Severe Storm
## 14            4800      2024-07-15    KS        Severe Storm
## 15            4799      2024-07-10    NH        Winter Storm
## 16            4798      2024-07-09    TX           Hurricane
## 17            4797      2024-06-28    MN               Flood
## 18            4796      2024-06-24    IA        Severe Storm
## 19            4795      2024-06-20    NM                Fire
## 20            4792      2024-06-17    TN        Severe Storm
## 21            4794      2024-06-17    FL        Severe Storm
## 22            4793      2024-06-17    HI               Flood
## 23            4791      2024-06-14    OK        Severe Storm
## 24            4790      2024-06-10    MS        Severe Storm
## 25            4789      2024-06-10    ID               Flood
## 26            4788      2024-05-30    AR        Severe Storm
## 27            4787      2024-05-24    WV               Flood
## 28            4786      2024-05-24    NE        Severe Storm
## 29            4785      2024-05-24    ME        Winter Storm
## 30            4784      2024-05-24    IA        Severe Storm
## 31            4783      2024-05-22    WV        Severe Storm
## 32            4782      2024-05-22    KY        Severe Storm
## 33            4781      2024-05-17    TX               Flood
## 34            4780      2024-05-15    MA               Flood
## 35            4779      2024-05-14    IA             Tornado
## 36            4778      2024-05-03    NE             Tornado
## 37            4777      2024-05-02    OH             Tornado
## 38            4776      2024-04-30    OK             Tornado
## 39            4775      2024-04-28    WA        Severe Storm
## 40            4774      2024-04-28    KS        Winter Storm
## 41            4773      2024-04-19    CA        Severe Storm
## 42            4772      2024-04-19    CA        Severe Storm
## 43            4771      2024-04-19    NH        Severe Storm
## 44            4770      2024-04-19    VT        Severe Storm
## 45            4769      2024-04-13    CA        Severe Storm
## 46            4768      2024-04-13    OR        Severe Storm
## 47            4767      2024-04-06    AK       Mud/Landslide
## 48            4766      2024-03-20    RI        Severe Storm
## 49            4765      2024-03-20    RI        Severe Storm
## 50            4764      2024-03-20    ME        Severe Storm
## 51            4763      2024-03-15    AK       Mud/Landslide
## 52            4762      2024-03-02    VT        Severe Storm
## 53            4761      2024-02-27    NH        Severe Storm
## 54            4758      2024-02-19    CA               Flood
## 55            4760      2024-02-15    ND        Winter Storm
## 56            4759      2024-02-15    WA                Fire
## 57            4757      2024-02-08    MI               Flood
## 58            4756      2024-01-30    WV               Flood
## 59            4755      2024-01-30    NY               Flood
## 60            4754      2024-01-30    ME        Severe Storm
## 61            4753      2024-01-07    RI        Severe Storm
## 62            4752      2023-12-23    UT               Flood
## 63            4751      2023-12-13    TN        Severe Storm
## 64            4750      2023-11-21    CA           Hurricane
## 65            4749      2023-11-20    IL               Flood
## 66            4748      2023-11-14    AR        Severe Storm
## 67            4747      2023-10-26    KS        Severe Storm
## 68            4746      2023-10-18    CA      Tropical Storm
## 69            4745      2023-10-11    MT               Flood
## 70            4744      2023-10-06    VT               Flood
## 71            4743      2023-09-27    CA           Hurricane
## 72            4742      2023-09-27    TN        Severe Storm
## 73            4741      2023-09-21    MO        Severe Storm
## 74            4740      2023-09-14    NH               Flood
## 75            4739      2023-09-11    WY               Flood
## 76            4738      2023-09-07    GA           Hurricane
## 77            4737      2023-09-06    ME               Flood
## 78            4736      2023-09-05    ME               Flood
## 79            4735      2023-09-04    TN        Severe Storm
## 80            4734      2023-08-31    FL           Hurricane
## 81            4733      2023-08-28    OR       Mud/Landslide
## 82            4732      2023-08-25    IA               Flood
## 83            4731      2023-08-25    CO               Flood
## 84            4730      2023-08-23    AK               Flood
## 85            4729      2023-08-17    TN        Severe Storm
## 86            4728      2023-08-15    IL        Severe Storm
## 87            4727      2023-08-12    MS        Severe Storm
## 88            4726      2023-08-12    MT               Flood
## 89            4725      2023-08-11    NJ        Severe Storm
## 90            4724      2023-08-10    HI                Fire
## 91            4723      2023-07-22    NY        Severe Storm
## 92            4722      2023-07-19    MN               Flood
## 93            4721      2023-07-19    OK        Severe Storm
## 94            4720      2023-07-14    VT               Flood
## 95            4719      2023-07-06    ME               Flood
## 96            4718      2023-07-06    SD               Flood
## 97            4717      2023-07-05    ND               Flood
## 98            4716      2023-06-02    MP      Tropical Storm
## 99            4715      2023-05-25    GU           Hurricane
## 100           4714      2023-05-25    CA        Severe Storm
## 101           4713      2023-05-18    CA        Severe Storm
## 102           4712      2023-05-17    TN        Severe Storm
## 103           4711      2023-05-09    KY               Flood
## 104           4710      2023-05-05    AL        Severe Storm
## 105           4709      2023-04-27    FL               Flood
## 106           4708      2023-04-27    NV               Flood
## 107           4707      2023-04-25    CA        Winter Storm
## 108           4706      2023-04-24    OK             Tornado
## 109           4705      2023-04-21    TX        Winter Storm
## 110           4704      2023-04-15    IN        Severe Storm
## 111           4703      2023-04-11    AZ        Severe Storm
## 112           4702      2023-04-10    KY        Severe Storm
## 113           4701      2023-04-07    TN        Severe Storm
## 114           4700      2023-04-04    AR        Winter Storm
## 115           4699      2023-04-03    CA        Severe Storm
## 116           4698      2023-04-02    AR        Severe Storm
## 117           4697      2023-03-26    MS        Severe Storm
## 118           4696      2023-03-22    ME        Severe Storm
## 119           4695      2023-03-20    VT        Severe Storm
## 120           4694      2023-03-15    NY           Snowstorm
## 121           4693      2023-03-15    NH        Severe Storm
## 122           4692      2023-03-08    CA          Earthquake
## 123           4691      2023-03-08    TN        Winter Storm
## 124           4690      2023-03-03    OK        Severe Storm
## 125           4689      2023-02-27    SD        Winter Storm
## 126           4688      2023-02-20    SD        Winter Storm
## 127           4687      2023-02-20    SD        Winter Storm
## 128           4686      2023-02-05    ND           Snowstorm
## 129           4685      2023-01-16    GA        Severe Storm
## 130           4684      2023-01-15    AL        Severe Storm
## 131           4683      2023-01-14    CA               Flood
## 132           4682      2023-01-12    WA        Severe Storm
##                                                                       declarationTitle
## 1                                                                  STRAIGHT-LINE WINDS
## 2                          SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 3                                                            SEVERE STORM AND FLOODING
## 4                           SEVERE STORM, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 5                                    SEVERE STORM, FLOODING, LANDSLIDES, AND MUDSLIDES
## 6                                                           SEVERE STORMS AND FLOODING
## 7                                     SEVERE STORMS, STRAIGHT-LINE WINDS, AND FLOODING
## 8                                                                      HURRICANE DEBBY
## 9             SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, LANDSLIDES, AND MUDSLIDES
## 10                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 11                                                                       SEVERE STORMS
## 12                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 13                                                    SEVERE WINTER STORM AND FLOODING
## 14                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 15                                                    SEVERE WINTER STORM AND FLOODING
## 16                                                                    HURRICANE BERYL 
## 17                                                          SEVERE STORMS AND FLOODING
## 18                         SEVERE STORMS, FLOODING, STRAIGHT-LINE WINDS, AND TORNADOES
## 19                                            SOUTH FORK FIRE, SALT FIRE, AND FLOODING
## 20                                              SEVERE STORMS, TORNADOES, AND FLOODING
## 21                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 22                                             SEVERE STORMS, FLOODING, AND LANDSLIDES
## 23                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 24                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 25                                   SEVERE STORM, FLOODING, LANDSLIDES, AND MUDSLIDES
## 26                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 27                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 28                                         SEVERE WINTER STORM AND STRAIGHT-LINE WINDS
## 29                                                                 SEVERE WINTER STORM
## 30                                              SEVERE STORMS, TORNADOES, AND FLOODING
## 31  SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, FLOODING, LANDSLIDES, AND MUDSLIDES
## 32            SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, LANDSLIDES, AND MUDSLIDES
## 33                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 34                                                          SEVERE STORMS AND FLOODING
## 35                                                         SEVERE STORMS AND TORNADOES
## 36                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 37                                                                           TORNADOES
## 38                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 39      SEVERE WINTER STORMS, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 40                                                                 SEVERE WINTER STORM
## 41                                                                 SEVERE WINTER STORM
## 42                                                          SEVERE STORMS AND FLOODING
## 43                                                          SEVERE STORMS AND FLOODING
## 44                                                                 SEVERE WINTER STORM
## 45                SEVERE WINTER STORMS, TORNADOES, FLOODING, LANDSLIDES, AND MUDSLIDES
## 46                SEVERE WINTER STORMS, STRAIGHT-LINE WINDS, LANDSLIDES, AND MUDSLIDES
## 47                                              SEVERE STORM, FLOODING, AND LANDSLIDES
## 48                                                          SEVERE STORMS AND FLOODING
## 49                                                           SEVERE STORM AND FLOODING
## 50                                                          SEVERE STORMS AND FLOODING
## 51                                             SEVERE STORM, LANDSLIDES, AND MUDSLIDES
## 52                                                           SEVERE STORM AND FLOODING
## 53                                                           SEVERE STORM AND FLOODING
## 54                                                           SEVERE STORM AND FLOODING
## 55                                         SEVERE WINTER STORM AND STRAIGHT-LINE WINDS
## 56                                                                           WILDFIRES
## 57                                              SEVERE STORMS, TORNADOES, AND FLOODING
## 58                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 59                                                           SEVERE STORM AND FLOODING
## 60                                                           SEVERE STORM AND FLOODING
## 61                                              SEVERE STORMS, FLOODING, AND TORNADOES
## 62                                                                            FLOODING
## 63                                                         SEVERE STORMS AND TORNADOES
## 64                                                               TROPICAL STORM HILARY
## 65                                                          SEVERE STORMS AND FLOODING
## 66                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 67                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 68                                                               TROPICAL STORM HILARY
## 69                                                                            FLOODING
## 70                                                          SEVERE STORMS AND FLOODING
## 71                                                               TROPICAL STORM HILARY
## 72                                     SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADO
## 73                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
## 74                                                          SEVERE STORMS AND FLOODING
## 75                                                                            FLOODING
## 76                                                                    HURRICANE IDALIA
## 77                                                           SEVERE STORM AND FLOODING
## 78                                                           SEVERE STORM AND FLOODING
## 79                                               SEVERE STORMS AND STRAIGHT-LINE WINDS
## 80                                                                    HURRICANE IDALIA
## 81                                   SEVERE STORM, FLOODING, LANDSLIDES, AND MUDSLIDES
## 82                                                                            FLOODING
## 83                                              SEVERE STORMS, FLOODING, AND TORNADOES
## 84                                                                            FLOODING
## 85                                               SEVERE STORMS AND STRAIGHT-LINE WINDS
## 86                                                          SEVERE STORMS AND FLOODING
## 87                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES.
## 88                                                                            FLOODING
## 89                                                           SEVERE STORM AND FLOODING
## 90                                                            WILDFIRES AND HIGH WINDS
## 91                                                          SEVERE STORMS AND FLOODING
## 92                                                          SEVERE STORMS AND FLOODING
## 93                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 94                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 95                                                           SEVERE STORM AND FLOODING
## 96                                                                            FLOODING
## 97                                                                            FLOODING
## 98                                                                       TYPHOON MAWAR
## 99                                                                       TYPHOON MAWAR
## 100                                                          SEVERE STORM AND FLOODING
## 101                                                   SEVERE WINTER STORM AND FLOODING
## 102                                    SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADO
## 103            SEVERE STORMS, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 104                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 105                                             SEVERE STORMS, TORNADOES, AND FLOODING
## 106                          SEVERE WINTER STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 107                                                 SEVERE WINTER STORMS AND MUDSLIDES
## 108                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 109                                                                SEVERE WINTER STORM
## 110                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 111                                                  SEVERE WINTER STORMS AND FLOODING
## 112 SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, FLOODING, LANDSLIDES, AND MUDSLIDES
## 113                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 114                                                                SEVERE WINTER STORM
## 115     SEVERE WINTER STORMS, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 116                                                        SEVERE STORMS AND TORNADOES
## 117                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 118                                                          SEVERE STORM AND FLOODING
## 119                                                          SEVERE STORM AND FLOODING
## 120                                                  SEVERE WINTER STORM AND SNOWSTORM
## 121                                                          SEVERE STORM AND FLOODING
## 122                                                                         EARTHQUAKE
## 123                                                                SEVERE WINTER STORM
## 124                                                                SEVERE WINTER STORM
## 125                                                 SEVERE WINTER STORMS AND SNOWSTORM
## 126                                                 SEVERE WINTER STORMS AND SNOWSTORM
## 127                                                 SEVERE WINTER STORMS AND SNOWSTORM
## 128                            SEVERE WINTER STORM, SNOWSTORM, AND STRAIGHT-LINE WINDS
## 129                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 130                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
## 131                          SEVERE WINTER STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
## 132      SEVERE WINTER STORM, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
# Load required libraries
library(httr)
library(jsonlite)
library(dplyr)
library(lubridate)
library(ggplot2)
library(maps)
library(scales)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:httr':
## 
##     config
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
# Function to fetch data from the API
fetch_fema_data <- function(url, declarationDate, limit = 1000, offset = 0) {
  query_params <- list(
    "$filter" = paste0("declarationDate ge '", declarationDate,
                       "' and (disasterNumber le 1999 or (disasterNumber ge 4000 and disasterNumber le 4999))"),
    "$orderby" = "declarationDate desc",
    "$top" = limit,
    "$skip" = offset
  )
  
  response <- GET(url, query = query_params)
  
  if (status_code(response) != 200) {
    stop("Failed to fetch data from the API. Status code: ", status_code(response))
  }
  
  content <- content(response, "text", encoding = "UTF-8")
  data <- fromJSON(content)
  
  return(data$DisasterDeclarationsSummaries)
}

# Main script
main <- function() {
  base_url <- "https://www.fema.gov/api/open/v2/DisasterDeclarationsSummaries"
  all_data <- data.frame()
  
  start_date <- "2023-01-01"
  chunk_size <- 1000
  
  cat("Fetching data from FEMA API...\n")
  
  offset <- 0
  repeat {
    cat(sprintf("Fetching records starting from offset %d\n", offset))
    chunk <- fetch_fema_data(base_url, start_date, chunk_size, offset)
    all_data <- bind_rows(all_data, chunk)
    
    if (nrow(chunk) < chunk_size) break
    offset <- offset + chunk_size
  }
  
  cat(sprintf("Total records fetched: %d\n", nrow(all_data)))
  
  # Convert declarationDate to Date type and disasterNumber to numeric
  all_data$declarationDate <- as.Date(all_data$declarationDate)
  all_data$disasterNumber <- as.numeric(all_data$disasterNumber)
  
  # Keep only unique disaster declarations
  filtered_data <- all_data %>%
    distinct(disasterNumber, .keep_all = TRUE)
  
  cat(sprintf("\nUnique major disaster declarations from %s to %s: %d\n",
              start_date, format(Sys.Date(), "%Y-%m-%d"), nrow(filtered_data)))
  
  # Analyze incident types
  incident_types <- filtered_data %>%
    group_by(incidentType) %>%
    summarise(count = n()) %>%
    arrange(desc(count))
  
  cat("\nIncident types for major disasters from 2023-01-01 onwards:\n")
  print(incident_types)
  
  # Count disasters by state and get additional information
  state_data <- filtered_data %>%
    group_by(state) %>%
    summarise(
      count = n(),
      most_common_incident = names(which.max(table(incidentType))),
      avg_days_to_declare = mean(as.numeric(declarationDate - as.Date(incidentBeginDate)), na.rm = TRUE),
      latest_disaster_date = max(declarationDate),
      latest_disaster_title = declarationTitle[which.max(declarationDate)]
    ) %>%
    arrange(desc(count))
  
  # Get US state map data
  us_states <- map_data("state")
  
  # Convert state abbreviations to full names for joining
  state_data$region <- tolower(state.name[match(state_data$state, state.abb)])
  
  # Join map data with state data
  map_data <- left_join(us_states, state_data, by = "region")
  
  # Create the base ggplot map
  p <- ggplot(data = map_data, aes(x = long, y = lat, group = group, fill = count,
                                   text = paste0("State: ", state, "<br>",
                                                "Disaster Count: ", count, "<br>",
                                                "Most Common Incident: ", most_common_incident, "<br>",
                                                "Avg Days to Declare: ", round(avg_days_to_declare, 1), "<br>",
                                                "Latest Disaster Date: ", latest_disaster_date, "<br>",
                                                "Latest Disaster: ", latest_disaster_title))) +
    geom_polygon(color = "white") +
    scale_fill_gradient(name = "Number of\nMajor Disasters",
                        low = "lightblue", high = "darkblue",
                        na.value = "grey90",
                        breaks = pretty_breaks(n = 5)) +
    coord_fixed(1.3) +
    theme_minimal() +
    labs(title = "FEMA Major Disaster Declarations by State (2023-01-01 onwards)",
         subtitle = paste("Total declarations:", sum(state_data$count, na.rm = TRUE)),
         caption = "Data source: FEMA Disaster Declarations Summaries") +
    theme(axis.title.x = element_blank(),
          axis.text.x = element_blank(),
          axis.ticks.x = element_blank(),
          axis.title.y = element_blank(),
          axis.text.y = element_blank(),
          axis.ticks.y = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank())
  
  # Convert ggplot to plotly
  interactive_map <- ggplotly(p, tooltip = "text")
  
  # Display the interactive map
  print(interactive_map)
  
  cat("Interactive map has been displayed in R\n")
  
  # Display summary of state counts
  cat("\nStates by number of major disaster declarations (2023-01-01 onwards):\n")
  print(state_data)
  
  # Additional analysis: Average number of days between incident begin and declaration
  avg_days_to_declaration <- mean(state_data$avg_days_to_declare, na.rm = TRUE)
  
  cat(sprintf("\nOverall average number of days between incident begin and declaration: %.2f\n", avg_days_to_declaration))
}

# Run the main function
main()
## Fetching data from FEMA API...
## Fetching records starting from offset 0
## Fetching records starting from offset 1000
## Total records fetched: 1592
## 
## Unique major disaster declarations from 2023-01-01 to 2024-08-28: 132
## 
## Incident types for major disasters from 2023-01-01 onwards:
## # A tibble: 11 × 2
##    incidentType        count
##    <chr>               <int>
##  1 Severe Storm           63
##  2 Flood                  34
##  3 Winter Storm           11
##  4 Hurricane               6
##  5 Tornado                 5
##  6 Fire                    3
##  7 Mud/Landslide           3
##  8 Tropical Storm          3
##  9 Snowstorm               2
## 10 Earthquake              1
## 11 Straight-Line Winds     1
## Interactive map has been displayed in R
## 
## States by number of major disaster declarations (2023-01-01 onwards):
## # A tibble: 44 × 7
##    state count most_common_incident avg_days_to_declare latest_disaster_date
##    <chr> <int> <chr>                              <dbl> <date>              
##  1 CA       13 Severe Storm                        63.1 2024-04-19          
##  2 TN        8 Severe Storm                        44.5 2024-06-17          
##  3 ME        7 Flood                               66   2024-05-24          
##  4 NH        6 Severe Storm                        77   2024-08-20          
##  5 OK        6 Severe Storm                        45.7 2024-07-23          
##  6 VT        6 Severe Storm                        62.8 2024-08-20          
##  7 SD        5 Winter Storm                        73   2024-08-15          
##  8 AR        4 Severe Storm                        53.5 2024-05-30          
##  9 FL        4 Flood                               16.5 2024-08-10          
## 10 IA        4 Severe Storm                        38.2 2024-06-24          
## # ℹ 34 more rows
## # ℹ 2 more variables: latest_disaster_title <chr>, region <chr>
## 
## Overall average number of days between incident begin and declaration: 68.90
# Load required libraries
library(httr)
library(jsonlite)
library(dplyr)
library(lubridate)
library(leaflet)
library(sf)
library(maps)

# Function to fetch data from the API
fetch_fema_data <- function(url, declarationDate, limit = 1000, offset = 0) {
  query_params <- list(
    "$filter" = paste0("declarationDate ge '", declarationDate,
                       "' and (disasterNumber le 1999 or (disasterNumber ge 4000 and disasterNumber le 4999))"),
    "$orderby" = "declarationDate desc",
    "$top" = limit,
    "$skip" = offset
  )
  
  response <- GET(url, query = query_params)
  
  if (status_code(response) != 200) {
    stop("Failed to fetch data from the API. Status code: ", status_code(response))
  }
  
  content <- content(response, "text", encoding = "UTF-8")
  data <- fromJSON(content)
  
  return(data$DisasterDeclarationsSummaries)
}

# Main script
main <- function() {
  base_url <- "https://www.fema.gov/api/open/v2/DisasterDeclarationsSummaries"
  all_data <- data.frame()
  
  start_date <- "2023-01-01"
  chunk_size <- 1000
  
  cat("Fetching data from FEMA API...\n")
  
  offset <- 0
  repeat {
    cat(sprintf("Fetching records starting from offset %d\n", offset))
    chunk <- fetch_fema_data(base_url, start_date, chunk_size, offset)
    all_data <- bind_rows(all_data, chunk)
    
    if (nrow(chunk) < chunk_size) break
    offset <- offset + chunk_size
  }
  
  cat(sprintf("Total records fetched: %d\n", nrow(all_data)))
  
  if (nrow(all_data) == 0) {
    stop("No data fetched from the API. Please check the API endpoint and parameters.")
  }
  
  # Convert date fields to Date type and numeric fields to appropriate types
  all_data$declarationDate <- as.Date(all_data$declarationDate)
  all_data$incidentBeginDate <- as.Date(all_data$incidentBeginDate)
  all_data$incidentEndDate <- as.Date(all_data$incidentEndDate)
  all_data$disasterNumber <- as.integer(all_data$disasterNumber)
  all_data$fyDeclared <- as.integer(all_data$fyDeclared)
  
  # Keep only unique disaster declarations
  filtered_data <- all_data %>%
    distinct(disasterNumber, .keep_all = TRUE)
  
  cat(sprintf("\nUnique major disaster declarations from %s to %s: %d\n",
              start_date, format(Sys.Date(), "%Y-%m-%d"), nrow(filtered_data)))
  
  # Analyze incident types
  incident_types <- filtered_data %>%
    group_by(incidentType) %>%
    summarise(count = n()) %>%
    arrange(desc(count))
  
  cat("\nIncident types for major disasters from 2023-01-01 onwards:\n")
  print(incident_types)
  
  # Count disasters by state and get additional information
  state_data <- filtered_data %>%
    group_by(state) %>%
    summarise(
      count = n(),
      most_common_incident = names(which.max(table(incidentType))),
      avg_days_to_declare = mean(as.numeric(declarationDate - incidentBeginDate), na.rm = TRUE),
      latest_disaster_date = max(declarationDate),
      latest_disaster_title = declarationTitle[which.max(declarationDate)],
      ia_program_count = sum(iaProgramDeclared, na.rm = TRUE),
      pa_program_count = sum(paProgramDeclared, na.rm = TRUE),
      hm_program_count = sum(hmProgramDeclared, na.rm = TRUE)
    ) %>%
    arrange(desc(count))
  
  cat("\nState data summary:\n")
  print(state_data)
  
  # Get US state map data
  us_states <- st_as_sf(maps::map("state", plot = FALSE, fill = TRUE))
  us_states$state_name <- toupper(us_states$ID)
  
  # Convert state abbreviations to full names for joining
  state_data$state_name <- tolower(state.name[match(state_data$state, state.abb)])
  
  # Join state data with map data
  map_data <- left_join(us_states, state_data, by = c("ID" = "state_name"))
  
  cat("\nMap data summary:\n")
  print(summary(map_data))
  
  if (all(is.na(map_data$count))) {
    stop("All count values are NA. Check the join between us_states and state_data.")
  }
  
  # Create color palette
  pal <- colorNumeric(
    palette = "YlOrRd",
    domain = map_data$count,
    na.color = "grey"
  )
  
  # Create Leaflet map
  m <- leaflet(map_data) %>%
    addTiles() %>%
    addPolygons(
      fillColor = ~pal(count),
      weight = 2,
      opacity = 1,
      color = "white",
      dashArray = "3",
      fillOpacity = 0.7,
      highlightOptions = highlightOptions(
        weight = 5,
        color = "#666",
        dashArray = "",
        fillOpacity = 0.7,
        bringToFront = TRUE),
      label = ~ID,
      popup = ~paste0(
        "<strong>", ID, "</strong><br>",
        "Disaster Count: ", count, "<br>",
        "Most Common Incident: ", most_common_incident, "<br>",
        "Avg Days to Declare: ", round(avg_days_to_declare, 1), "<br>",
        "Latest Disaster Date: ", latest_disaster_date, "<br>",
        "Latest Disaster: ", latest_disaster_title, "<br>",
        "IA Program Declared: ", ia_program_count, "<br>",
        "PA Program Declared: ", pa_program_count, "<br>",
        "HM Program Declared: ", hm_program_count
      )
    ) %>%
    addLegend(pal = pal,
              values = ~count,
              opacity = 0.7,
              title = "Number of Major Disasters",
              position = "bottomright")
  
  cat("Interactive Leaflet map has been created\n")
  
  # Display summary of state counts
  cat("\nStates by number of major disaster declarations (2023-01-01 onwards):\n")
  print(state_data)
  
  # Additional analysis: Average number of days between incident begin and declaration
  avg_days_to_declaration <- mean(state_data$avg_days_to_declare, na.rm = TRUE)
  
  cat(sprintf("\nOverall average number of days between incident begin and declaration: %.2f\n", avg_days_to_declaration))
  
  # List of disaster declarations
  cat("\nList of major disaster declarations from 2023-01-01 onwards:\n")
  disaster_list <- filtered_data %>%
    select(disasterNumber, declarationDate, state, incidentType, declarationTitle,
           iaProgramDeclared, paProgramDeclared, hmProgramDeclared) %>%
    arrange(desc(declarationDate))
  print(disaster_list, na.print = "NA", row.names = FALSE)
  
  # Return the Leaflet map object
  return(m)
}

# Run the main function and store the result
result <- main()
## Fetching data from FEMA API...
## Fetching records starting from offset 0
## Fetching records starting from offset 1000
## Total records fetched: 1592
## 
## Unique major disaster declarations from 2023-01-01 to 2024-08-28: 132
## 
## Incident types for major disasters from 2023-01-01 onwards:
## # A tibble: 11 × 2
##    incidentType        count
##    <chr>               <int>
##  1 Severe Storm           63
##  2 Flood                  34
##  3 Winter Storm           11
##  4 Hurricane               6
##  5 Tornado                 5
##  6 Fire                    3
##  7 Mud/Landslide           3
##  8 Tropical Storm          3
##  9 Snowstorm               2
## 10 Earthquake              1
## 11 Straight-Line Winds     1
## 
## State data summary:
## # A tibble: 44 × 9
##    state count most_common_incident avg_days_to_declare latest_disaster_date
##    <chr> <int> <chr>                              <dbl> <date>              
##  1 CA       13 Severe Storm                        63.1 2024-04-19          
##  2 TN        8 Severe Storm                        44.5 2024-06-17          
##  3 ME        7 Flood                               66   2024-05-24          
##  4 NH        6 Severe Storm                        77   2024-08-20          
##  5 OK        6 Severe Storm                        45.7 2024-07-23          
##  6 VT        6 Severe Storm                        62.8 2024-08-20          
##  7 SD        5 Winter Storm                        73   2024-08-15          
##  8 AR        4 Severe Storm                        53.5 2024-05-30          
##  9 FL        4 Flood                               16.5 2024-08-10          
## 10 IA        4 Severe Storm                        38.2 2024-06-24          
## # ℹ 34 more rows
## # ℹ 4 more variables: latest_disaster_title <chr>, ia_program_count <int>,
## #   pa_program_count <int>, hm_program_count <int>
## 
## Map data summary:
##       ID             state_name           state               count       
##  Length:49          Length:49          Length:49          Min.   : 1.000  
##  Class :character   Class :character   Class :character   1st Qu.: 1.000  
##  Mode  :character   Mode  :character   Mode  :character   Median : 3.000  
##                                                           Mean   : 3.179  
##                                                           3rd Qu.: 4.000  
##                                                           Max.   :13.000  
##                                                           NA's   :10      
##  most_common_incident avg_days_to_declare latest_disaster_date
##  Length:49            Min.   :  6.00      Min.   :2023-04-11  
##  Class :character     1st Qu.: 45.08      1st Qu.:2024-01-11  
##  Mode  :character     Median : 59.50      Median :2024-05-24  
##                       Mean   : 71.26      Mean   :2024-03-21  
##                       3rd Qu.: 84.33      3rd Qu.:2024-07-23  
##                       Max.   :247.00      Max.   :2024-08-23  
##                       NA's   :10          NA's   :10          
##  latest_disaster_title ia_program_count pa_program_count hm_program_count
##  Length:49             Min.   :0        Min.   : 0.000   Min.   : 1.000  
##  Class :character      1st Qu.:0        1st Qu.: 1.000   1st Qu.: 1.000  
##  Mode  :character      Median :0        Median : 2.000   Median : 3.000  
##                        Mean   :0        Mean   : 2.923   Mean   : 3.154  
##                        3rd Qu.:0        3rd Qu.: 4.000   3rd Qu.: 4.000  
##                        Max.   :0        Max.   :12.000   Max.   :13.000  
##                        NA's   :10       NA's   :10       NA's   :10      
##             geom   
##  MULTIPOLYGON :49  
##  epsg:NA      : 0  
##  +proj=long...: 0  
##                    
##                    
##                    
##                    
## Interactive Leaflet map has been created
## 
## States by number of major disaster declarations (2023-01-01 onwards):
## # A tibble: 44 × 10
##    state count most_common_incident avg_days_to_declare latest_disaster_date
##    <chr> <int> <chr>                              <dbl> <date>              
##  1 CA       13 Severe Storm                        63.1 2024-04-19          
##  2 TN        8 Severe Storm                        44.5 2024-06-17          
##  3 ME        7 Flood                               66   2024-05-24          
##  4 NH        6 Severe Storm                        77   2024-08-20          
##  5 OK        6 Severe Storm                        45.7 2024-07-23          
##  6 VT        6 Severe Storm                        62.8 2024-08-20          
##  7 SD        5 Winter Storm                        73   2024-08-15          
##  8 AR        4 Severe Storm                        53.5 2024-05-30          
##  9 FL        4 Flood                               16.5 2024-08-10          
## 10 IA        4 Severe Storm                        38.2 2024-06-24          
## # ℹ 34 more rows
## # ℹ 5 more variables: latest_disaster_title <chr>, ia_program_count <int>,
## #   pa_program_count <int>, hm_program_count <int>, state_name <chr>
## 
## Overall average number of days between incident begin and declaration: 68.90
## 
## List of major disaster declarations from 2023-01-01 onwards:
##  disasterNumber declarationDate state        incidentType
##            4813      2024-08-23    MT Straight-Line Winds
##            4808      2024-08-20    NE        Severe Storm
##            4812      2024-08-20    NH        Severe Storm
##            4811      2024-08-20    KS        Severe Storm
##            4810      2024-08-20    VT        Severe Storm
##            4809      2024-08-20    NM               Flood
##            4807      2024-08-15    SD               Flood
##            4806      2024-08-10    FL      Tropical Storm
##            4804      2024-07-23    KY        Severe Storm
##            4803      2024-07-23    MO        Severe Storm
##            4802      2024-07-23    OK        Severe Storm
##            4805      2024-07-23    PR               Flood
##            4801      2024-07-18    MT        Severe Storm
##            4800      2024-07-15    KS        Severe Storm
##            4799      2024-07-10    NH        Winter Storm
##            4798      2024-07-09    TX           Hurricane
##            4797      2024-06-28    MN               Flood
##            4796      2024-06-24    IA        Severe Storm
##            4795      2024-06-20    NM                Fire
##            4792      2024-06-17    TN        Severe Storm
##            4794      2024-06-17    FL        Severe Storm
##            4793      2024-06-17    HI               Flood
##            4791      2024-06-14    OK        Severe Storm
##            4790      2024-06-10    MS        Severe Storm
##            4789      2024-06-10    ID               Flood
##            4788      2024-05-30    AR        Severe Storm
##            4787      2024-05-24    WV               Flood
##            4786      2024-05-24    NE        Severe Storm
##            4785      2024-05-24    ME        Winter Storm
##            4784      2024-05-24    IA        Severe Storm
##            4783      2024-05-22    WV        Severe Storm
##            4782      2024-05-22    KY        Severe Storm
##            4781      2024-05-17    TX               Flood
##            4780      2024-05-15    MA               Flood
##            4779      2024-05-14    IA             Tornado
##            4778      2024-05-03    NE             Tornado
##            4777      2024-05-02    OH             Tornado
##            4776      2024-04-30    OK             Tornado
##            4775      2024-04-28    WA        Severe Storm
##            4774      2024-04-28    KS        Winter Storm
##            4773      2024-04-19    CA        Severe Storm
##            4772      2024-04-19    CA        Severe Storm
##            4771      2024-04-19    NH        Severe Storm
##            4770      2024-04-19    VT        Severe Storm
##            4769      2024-04-13    CA        Severe Storm
##            4768      2024-04-13    OR        Severe Storm
##            4767      2024-04-06    AK       Mud/Landslide
##            4766      2024-03-20    RI        Severe Storm
##            4765      2024-03-20    RI        Severe Storm
##            4764      2024-03-20    ME        Severe Storm
##            4763      2024-03-15    AK       Mud/Landslide
##            4762      2024-03-02    VT        Severe Storm
##            4761      2024-02-27    NH        Severe Storm
##            4758      2024-02-19    CA               Flood
##            4760      2024-02-15    ND        Winter Storm
##            4759      2024-02-15    WA                Fire
##            4757      2024-02-08    MI               Flood
##            4756      2024-01-30    WV               Flood
##            4755      2024-01-30    NY               Flood
##            4754      2024-01-30    ME        Severe Storm
##            4753      2024-01-07    RI        Severe Storm
##            4752      2023-12-23    UT               Flood
##            4751      2023-12-13    TN        Severe Storm
##            4750      2023-11-21    CA           Hurricane
##            4749      2023-11-20    IL               Flood
##            4748      2023-11-14    AR        Severe Storm
##            4747      2023-10-26    KS        Severe Storm
##            4746      2023-10-18    CA      Tropical Storm
##            4745      2023-10-11    MT               Flood
##            4744      2023-10-06    VT               Flood
##            4743      2023-09-27    CA           Hurricane
##            4742      2023-09-27    TN        Severe Storm
##            4741      2023-09-21    MO        Severe Storm
##            4740      2023-09-14    NH               Flood
##            4739      2023-09-11    WY               Flood
##            4738      2023-09-07    GA           Hurricane
##            4737      2023-09-06    ME               Flood
##            4736      2023-09-05    ME               Flood
##            4735      2023-09-04    TN        Severe Storm
##            4734      2023-08-31    FL           Hurricane
##            4733      2023-08-28    OR       Mud/Landslide
##            4732      2023-08-25    IA               Flood
##            4731      2023-08-25    CO               Flood
##            4730      2023-08-23    AK               Flood
##            4729      2023-08-17    TN        Severe Storm
##            4728      2023-08-15    IL        Severe Storm
##            4727      2023-08-12    MS        Severe Storm
##            4726      2023-08-12    MT               Flood
##            4725      2023-08-11    NJ        Severe Storm
##            4724      2023-08-10    HI                Fire
##            4723      2023-07-22    NY        Severe Storm
##            4722      2023-07-19    MN               Flood
##            4721      2023-07-19    OK        Severe Storm
##            4720      2023-07-14    VT               Flood
##            4719      2023-07-06    ME               Flood
##            4718      2023-07-06    SD               Flood
##            4717      2023-07-05    ND               Flood
##            4716      2023-06-02    MP      Tropical Storm
##            4715      2023-05-25    GU           Hurricane
##            4714      2023-05-25    CA        Severe Storm
##            4713      2023-05-18    CA        Severe Storm
##            4712      2023-05-17    TN        Severe Storm
##            4711      2023-05-09    KY               Flood
##            4710      2023-05-05    AL        Severe Storm
##            4709      2023-04-27    FL               Flood
##            4708      2023-04-27    NV               Flood
##            4707      2023-04-25    CA        Winter Storm
##            4706      2023-04-24    OK             Tornado
##            4705      2023-04-21    TX        Winter Storm
##            4704      2023-04-15    IN        Severe Storm
##            4703      2023-04-11    AZ        Severe Storm
##            4702      2023-04-10    KY        Severe Storm
##            4701      2023-04-07    TN        Severe Storm
##            4700      2023-04-04    AR        Winter Storm
##            4699      2023-04-03    CA        Severe Storm
##            4698      2023-04-02    AR        Severe Storm
##            4697      2023-03-26    MS        Severe Storm
##            4696      2023-03-22    ME        Severe Storm
##            4695      2023-03-20    VT        Severe Storm
##            4694      2023-03-15    NY           Snowstorm
##            4693      2023-03-15    NH        Severe Storm
##            4692      2023-03-08    CA          Earthquake
##            4691      2023-03-08    TN        Winter Storm
##            4690      2023-03-03    OK        Severe Storm
##            4689      2023-02-27    SD        Winter Storm
##            4688      2023-02-20    SD        Winter Storm
##            4687      2023-02-20    SD        Winter Storm
##            4686      2023-02-05    ND           Snowstorm
##            4685      2023-01-16    GA        Severe Storm
##            4684      2023-01-15    AL        Severe Storm
##            4683      2023-01-14    CA               Flood
##            4682      2023-01-12    WA        Severe Storm
##                                                                    declarationTitle
##                                                                 STRAIGHT-LINE WINDS
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                          SEVERE STORM, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                   SEVERE STORM, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                          SEVERE STORMS AND FLOODING
##                                    SEVERE STORMS, STRAIGHT-LINE WINDS, AND FLOODING
##                                                                     HURRICANE DEBBY
##            SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, LANDSLIDES, AND MUDSLIDES
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                                                       SEVERE STORMS
##                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                    SEVERE WINTER STORM AND FLOODING
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                                    SEVERE WINTER STORM AND FLOODING
##                                                                    HURRICANE BERYL 
##                                                          SEVERE STORMS AND FLOODING
##                         SEVERE STORMS, FLOODING, STRAIGHT-LINE WINDS, AND TORNADOES
##                                            SOUTH FORK FIRE, SALT FIRE, AND FLOODING
##                                              SEVERE STORMS, TORNADOES, AND FLOODING
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                             SEVERE STORMS, FLOODING, AND LANDSLIDES
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                   SEVERE STORM, FLOODING, LANDSLIDES, AND MUDSLIDES
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                         SEVERE WINTER STORM AND STRAIGHT-LINE WINDS
##                                                                 SEVERE WINTER STORM
##                                              SEVERE STORMS, TORNADOES, AND FLOODING
##  SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, FLOODING, LANDSLIDES, AND MUDSLIDES
##            SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, LANDSLIDES, AND MUDSLIDES
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                                          SEVERE STORMS AND FLOODING
##                                                         SEVERE STORMS AND TORNADOES
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                                                           TORNADOES
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##      SEVERE WINTER STORMS, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                                 SEVERE WINTER STORM
##                                                                 SEVERE WINTER STORM
##                                                          SEVERE STORMS AND FLOODING
##                                                          SEVERE STORMS AND FLOODING
##                                                                 SEVERE WINTER STORM
##                SEVERE WINTER STORMS, TORNADOES, FLOODING, LANDSLIDES, AND MUDSLIDES
##                SEVERE WINTER STORMS, STRAIGHT-LINE WINDS, LANDSLIDES, AND MUDSLIDES
##                                              SEVERE STORM, FLOODING, AND LANDSLIDES
##                                                          SEVERE STORMS AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                                          SEVERE STORMS AND FLOODING
##                                             SEVERE STORM, LANDSLIDES, AND MUDSLIDES
##                                                           SEVERE STORM AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                         SEVERE WINTER STORM AND STRAIGHT-LINE WINDS
##                                                                           WILDFIRES
##                                              SEVERE STORMS, TORNADOES, AND FLOODING
##                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                           SEVERE STORM AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                              SEVERE STORMS, FLOODING, AND TORNADOES
##                                                                            FLOODING
##                                                         SEVERE STORMS AND TORNADOES
##                                                               TROPICAL STORM HILARY
##                                                          SEVERE STORMS AND FLOODING
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                                               TROPICAL STORM HILARY
##                                                                            FLOODING
##                                                          SEVERE STORMS AND FLOODING
##                                                               TROPICAL STORM HILARY
##                                     SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADO
##                         SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, AND FLOODING
##                                                          SEVERE STORMS AND FLOODING
##                                                                            FLOODING
##                                                                    HURRICANE IDALIA
##                                                           SEVERE STORM AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                               SEVERE STORMS AND STRAIGHT-LINE WINDS
##                                                                    HURRICANE IDALIA
##                                   SEVERE STORM, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                                            FLOODING
##                                              SEVERE STORMS, FLOODING, AND TORNADOES
##                                                                            FLOODING
##                                               SEVERE STORMS AND STRAIGHT-LINE WINDS
##                                                          SEVERE STORMS AND FLOODING
##                                  SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES.
##                                                                            FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                                            WILDFIRES AND HIGH WINDS
##                                                          SEVERE STORMS AND FLOODING
##                                                          SEVERE STORMS AND FLOODING
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                  SEVERE STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                           SEVERE STORM AND FLOODING
##                                                                            FLOODING
##                                                                            FLOODING
##                                                                       TYPHOON MAWAR
##                                                                       TYPHOON MAWAR
##                                                           SEVERE STORM AND FLOODING
##                                                    SEVERE WINTER STORM AND FLOODING
##                                     SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADO
##             SEVERE STORMS, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                              SEVERE STORMS, TORNADOES, AND FLOODING
##                           SEVERE WINTER STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                  SEVERE WINTER STORMS AND MUDSLIDES
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                                                 SEVERE WINTER STORM
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                                   SEVERE WINTER STORMS AND FLOODING
##  SEVERE STORMS, STRAIGHT-LINE WINDS, TORNADOES, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                                                 SEVERE WINTER STORM
##      SEVERE WINTER STORMS, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
##                                                         SEVERE STORMS AND TORNADOES
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                                           SEVERE STORM AND FLOODING
##                                                           SEVERE STORM AND FLOODING
##                                                   SEVERE WINTER STORM AND SNOWSTORM
##                                                           SEVERE STORM AND FLOODING
##                                                                          EARTHQUAKE
##                                                                 SEVERE WINTER STORM
##                                                                 SEVERE WINTER STORM
##                                                  SEVERE WINTER STORMS AND SNOWSTORM
##                                                  SEVERE WINTER STORMS AND SNOWSTORM
##                                                  SEVERE WINTER STORMS AND SNOWSTORM
##                             SEVERE WINTER STORM, SNOWSTORM, AND STRAIGHT-LINE WINDS
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                                   SEVERE STORMS, STRAIGHT-LINE WINDS, AND TORNADOES
##                           SEVERE WINTER STORMS, FLOODING, LANDSLIDES, AND MUDSLIDES
##       SEVERE WINTER STORM, STRAIGHT-LINE WINDS, FLOODING, LANDSLIDES, AND MUDSLIDES
##  iaProgramDeclared paProgramDeclared hmProgramDeclared
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE             FALSE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE             FALSE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
##              FALSE              TRUE              TRUE
# Display the Leaflet map
print(result)