# Load necessary libraries
library(dplyr)
library(ggplot2)
library(lubridate)
library(scales) # For formatting numbers
# Load the storm data
storm_data <- read.csv("repdata_data_StormData.csv")
# Check the structure of the data
str(storm_data[,1:10]) # First 10 columns for brevity
## 'data.frame':    902297 obs. of  10 variables:
##  $ STATE__   : num  1 1 1 1 1 1 1 1 1 1 ...
##  $ BGN_DATE  : chr  "4/18/1950 0:00:00" "4/18/1950 0:00:00" "2/20/1951 0:00:00" "6/8/1951 0:00:00" ...
##  $ BGN_TIME  : chr  "0130" "0145" "1600" "0900" ...
##  $ TIME_ZONE : chr  "CST" "CST" "CST" "CST" ...
##  $ COUNTY    : num  97 3 57 89 43 77 9 123 125 57 ...
##  $ COUNTYNAME: chr  "MOBILE" "BALDWIN" "FAYETTE" "MADISON" ...
##  $ STATE     : chr  "AL" "AL" "AL" "AL" ...
##  $ EVTYPE    : chr  "TORNADO" "TORNADO" "TORNADO" "TORNADO" ...
##  $ BGN_RANGE : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ BGN_AZI   : chr  "" "" "" "" ...
summary(storm_data[,c("FATALITIES", "INJURIES", "PROPDMG", "CROPDMG")])
##    FATALITIES          INJURIES            PROPDMG           CROPDMG       
##  Min.   :  0.0000   Min.   :   0.0000   Min.   :   0.00   Min.   :  0.000  
##  1st Qu.:  0.0000   1st Qu.:   0.0000   1st Qu.:   0.00   1st Qu.:  0.000  
##  Median :  0.0000   Median :   0.0000   Median :   0.00   Median :  0.000  
##  Mean   :  0.0168   Mean   :   0.1557   Mean   :  12.06   Mean   :  1.527  
##  3rd Qu.:  0.0000   3rd Qu.:   0.0000   3rd Qu.:   0.50   3rd Qu.:  0.000  
##  Max.   :583.0000   Max.   :1700.0000   Max.   :5000.00   Max.   :990.000
# Function to convert damage values with exponents
convert_damage <- function(dmg, exp) {
  exp <- toupper(as.character(exp))
  multiplier <- case_when(
    exp == "K" ~ 1000,
    exp == "M" ~ 1000000,
    exp == "B" ~ 1000000000,
    exp %in% c("", "+", "-", "?") ~ 1,
    TRUE ~ 1 # Default for unrecognized exponents
  )
  return(dmg * multiplier)
}

# Clean and prepare data
storm_data_clean <- storm_data %>%
  # Select needed columns
  select(EVTYPE, FATALITIES, INJURIES, PROPDMG, PROPDMGEXP, CROPDMG, CROPDMGEXP) %>%
  # Remove rows with missing event type
  filter(!is.na(EVTYPE) & EVTYPE != "") %>%
  # Standardize event types
  mutate(
    EVTYPE = toupper(EVTYPE),
    EVTYPE = case_when(
      grepl("TORNADO|TORNDAO", EVTYPE) ~ "TORNADO",
      grepl("HEAT|HOT", EVTYPE) ~ "EXCESSIVE HEAT",
      grepl("HURRICANE|TYPHOON", EVTYPE) ~ "HURRICANE/TYPHOON",
      grepl("FLOOD|FLD", EVTYPE) ~ "FLOOD",
      grepl("WIND|WND", EVTYPE) ~ "WIND",
      grepl("SNOW|WINTER|ICE", EVTYPE) ~ "WINTER WEATHER",
      grepl("RAIN|PRECIP", EVTYPE) ~ "HEAVY RAIN",
      TRUE ~ EVTYPE
    ),
    # Convert damage values
    PROPDMG = convert_damage(PROPDMG, PROPDMGEXP),
    CROPDMG = convert_damage(CROPDMG, CROPDMGEXP)
  )
# Health impact analysis
health_impact <- storm_data_clean %>%
  group_by(EVTYPE) %>%
  summarise(
    total_fatalities = sum(FATALITIES), 
    total_injuries = sum(INJURIES),
    total_health_impact = sum(FATALITIES + INJURIES)
  ) %>%
  arrange(desc(total_health_impact))

# Show top 10 events by health impact
health_top10 <- head(health_impact, 10)
health_top10 %>%
  mutate(across(where(is.numeric), ~ format(., big.mark = ",")))
## # A tibble: 10 × 4
##    EVTYPE            total_fatalities total_injuries total_health_impact
##    <chr>             <chr>            <chr>          <chr>              
##  1 TORNADO           "5,661"          "91,407"       "97,068"           
##  2 WIND              "1,424"          "11,498"       "12,922"           
##  3 EXCESSIVE HEAT    "3,138"          " 9,224"       "12,362"           
##  4 FLOOD             "1,553"          " 8,683"       "10,236"           
##  5 LIGHTNING         "  816"          " 5,230"       " 6,046"           
##  6 WINTER WEATHER    "  538"          " 5,151"       " 5,689"           
##  7 HURRICANE/TYPHOON "  135"          " 1,333"       " 1,468"           
##  8 HAIL              "   15"          " 1,361"       " 1,376"           
##  9 WILDFIRE          "   75"          "   911"       "   986"           
## 10 BLIZZARD          "  101"          "   805"       "   906"
# Economic impact analysis (in billions)
economic_impact <- storm_data_clean %>%
  group_by(EVTYPE) %>%
  summarise(
    property_damage_billions = sum(PROPDMG) / 1000000000,
    crop_damage_billions = sum(CROPDMG) / 1000000000,
    total_damage_billions = (sum(PROPDMG) + sum(CROPDMG)) / 1000000000
  ) %>%
  arrange(desc(total_damage_billions))

# Show top 10 events by economic impact
economic_top10 <- head(economic_impact, 10)
economic_top10 %>%
  mutate(across(where(is.numeric), ~ paste0("$", round(., 2), "B")))
## # A tibble: 10 × 4
##    EVTYPE      property_damage_bill…¹ crop_damage_billions total_damage_billions
##    <chr>       <chr>                  <chr>                <chr>                
##  1 FLOOD       $167.59B               $12.39B              $179.98B             
##  2 HURRICANE/… $85.36B                $5.52B               $90.87B              
##  3 TORNADO     $58.59B                $0.42B               $59.01B              
##  4 STORM SURGE $43.32B                $0B                  $43.32B              
##  5 HAIL        $15.73B                $3.03B               $18.76B              
##  6 WIND        $16.04B                $2.03B               $18.07B              
##  7 WINTER WEA… $11.7B                 $5.2B                $16.9B               
##  8 DROUGHT     $1.05B                 $13.97B              $15.02B              
##  9 TROPICAL S… $7.7B                  $0.68B               $8.38B               
## 10 WILDFIRE    $4.77B                 $0.3B                $5.06B               
## # ℹ abbreviated name: ¹​property_damage_billions
# Plot health impact
ggplot(health_top10, 
       aes(x = reorder(EVTYPE, total_health_impact), 
           y = total_health_impact)) +
  geom_bar(stat = "identity", fill = "red", alpha = 0.8) +
  geom_text(aes(label = comma(total_health_impact)), 
            hjust = -0.1, size = 3.5) +
  coord_flip() +
  scale_y_continuous(labels = comma, expand = expansion(mult = c(0, 0.1))) +
  labs(x = "Event Type", 
       y = "Total Fatalities + Injuries", 
       title = "Top 10 Most Harmful Weather Events to Population Health") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))

# Plot economic impact
ggplot(economic_top10, 
       aes(x = reorder(EVTYPE, total_damage_billions), 
           y = total_damage_billions)) +
  geom_bar(stat = "identity", fill = "blue", alpha = 0.8) +
  geom_text(aes(label = paste0("$", round(total_damage_billions, 1), "B")), 
            hjust = -0.1, size = 3.5) +
  coord_flip() +
  scale_y_continuous(labels = dollar_format(suffix = "B"), 
                     expand = expansion(mult = c(0, 0.1))) +
  labs(x = "Event Type", 
       y = "Total Damage (Billions USD)", 
       title = "Top 10 Most Costly Weather Events") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))

# Save processed data
save(health_impact, economic_impact, file = "weather_analysis_results.RData")
# Key findings
cat("## Key Findings\n\n")
## ## Key Findings
cat("1. **Health Impact**: Tornadoes cause the most harm with", 
    format(sum(health_top10$total_health_impact[1]), big.mark = ","), 
    "total casualties (fatalities + injuries).\n\n")
## 1. **Health Impact**: Tornadoes cause the most harm with 97,068 total casualties (fatalities + injuries).
cat("2. **Economic Impact**: Floods are the most costly weather events causing approximately $", 
    round(economic_top10$total_damage_billions[1], 1), 
    " billion in total damage.\n\n")
## 2. **Economic Impact**: Floods are the most costly weather events causing approximately $ 180  billion in total damage.
cat("3. **Pattern**: Hydrological events (floods) and meteorological events (tornadoes, hurricanes) dominate both health and economic impact categories.")
## 3. **Pattern**: Hydrological events (floods) and meteorological events (tornadoes, hurricanes) dominate both health and economic impact categories.