We download the raw data compressed file, load it into R, and process the variables to extract valid aggregates.
library(dplyr)
library(ggplot2)
library(tidyr)
# Download and load data if it doesn't exist
url <- "https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2FStormData.csv.bz2"
archive_file <- "StormData.csv.bz2"
if (!file.exists(archive_file)) {
download.file(url, archive_file, method = "libcurl")
}
# Read data (this can take a moment)
raw_data <- read.csv(archive_file)
# Cleaning Economic Damage Exponents
# Function to convert exponential codes to numeric multiplier values
get_multiplier <- function(exp) {
exp <- toupper(trimws(as.character(exp)))
if (exp == "B") return(1e9)
if (exp == "M") return(1e6)
if (exp == "K") return(1e3)
if (exp == "H") return(1e2)
if (exp %in% c("", "-", "?", "+")) return(1)
if (exp %in% as.character(0:8)) return(10)
return(1)
}
# Vectorize the function to run efficiently over the columns
v_get_multiplier <- Vectorize(get_multiplier)
# Select relevant columns and calculate true costs
processed_data <- raw_data %>%
select(EVTYPE, FATALITIES, INJURIES, PROPDMG, PROPDMGEXP, CROPDMG, CROPDMGEXP) %>%
mutate(
prop_mult = v_get_multiplier(PROPDMGEXP),
crop_mult = v_get_multiplier(CROPDMGEXP),
TOTAL_PROP_COST = PROPDMG * prop_mult,
TOTAL_CROP_COST = CROPDMG * crop_mult,
TOTAL_ECON_COST = TOTAL_PROP_COST + TOTAL_CROP_COST
)
# Public Health Impact
health_summary <- processed_data %>%
group_by(EVTYPE) %>%
summarize(
Total_Fatalities = sum(FATALITIES, na.rm = TRUE),
Total_Injuries = sum(INJURIES, na.rm = TRUE),
Total_Casualties = Total_Fatalities + Total_Injuries
) %>%
arrange(desc(Total_Casualties)) %>%
slice_head(n = 10)
# Reshape data for stacked visual presentation
health_long <- health_summary %>%
pivot_longer(cols = c(Total_Fatalities, Total_Injuries),
names_to = "Casualty_Type",
values_to = "Count")
ggplot(health_long, aes(x = reorder(EVTYPE, -Count), y = Count, fill = Casualty_Type)) +
geom_bar(stat = "identity") +
coord_flip() +
labs(
title = "Top 10 Most Harmful Severe Weather Events to Public Health",
x = "Event Type",
y = "Total Number of Casualties",
fill = "Casualty Metric"
) +
theme_minimal()
# Economic Impact
econ_summary <- processed_data %>%
group_by(EVTYPE) %>%
summarize(
Total_Property = sum(TOTAL_PROP_COST, na.rm = TRUE),
Total_Crop = sum(TOTAL_CROP_COST, na.rm = TRUE),
Total_Damage = sum(TOTAL_ECON_COST, na.rm = TRUE)
) %>%
arrange(desc(Total_Damage)) %>%
slice_head(n = 10)
ggplot(econ_summary, aes(x = reorder(EVTYPE, Total_Damage), y = Total_Damage / 1e9)) +
geom_bar(stat = "identity", fill = "darkgreen") +
coord_flip() +
labs(
title = "Top 10 Severe Weather Events with Highest Economic Cost",
x = "Event Type",
y = "Total Damage Cost (in Billions of USD)"
) +
theme_minimal()