RequiredPackages = c("rlang"
,"plyr"
,"dplyr"
,"tidyr"
,"ggplot2"
,"readr"
,"kableExtra"
,"knitr",
"rsconnect")
#This function performs a number of initializations:
# Load useful packages
# Empty variables
# Define directories of interest
# Import local functions of interest
if (!"install.load"%in%installed.packages()) {
install.packages("install.load", repos = "https://cloud.r-project.org")
}
library(install.load)
install_load(RequiredPackages)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:plyr':
##
## arrange, count, desc, failwith, id, mutate, rename, summarise,
## summarize
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
##
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
##
## group_rows
In this analysis, we explore the primary contributors to the loss of life and property during extreme weather events in the United States. Utilizing data collected from the National Weather Service, our findings reveal that a small set of fewer than 10 types of weather events account for more than two-thirds of all injuries, fatalities, and property damage caused by extreme weather. Notably, tornadoes and extreme heat emerge as the most significant threats to public safety, while floods, hurricanes, and storm surges are major contributors to property damage. Our study concludes with a preliminary analysis hinting at potential correlations between storm surges and hurricanes, encouraging further investigation.
“In this analysis, we utilize the US NOAA storm events database, accessible at https://www.ncdc.noaa.gov/stormevents/. The dataset, comprising 902,297 observations across 37 variables, documents significant weather events in the United States from 1950 to November 2011. To manage the large dataset, we selectively read in specific variables. The following R code identifies the appropriate columns for extraction.”
header <- read.csv("C:/Users/Louis Hognon/Documents/Reproductible research/repdata_data_StormData.csv.bz2", nrow = 10)
include <- which(names(header) %in% c("BGN_DATE", "EVTYPE",
"FATALITIES", "INJURIES",
"PROPDMG", "PROPDMGEXP", "CROPDMG", "CROPDMGEXP",
"LATITUDE", "LONGITUDE"))
columns <- rep("NULL", length(names(header)))
for(i in 1:length(columns)){
if(i %in% include){
columns[i] = NA
}
}
dataset <- read.csv("C:/Users/Louis Hognon/Documents/Reproductible research/repdata_data_StormData.csv.bz2", colClasses = columns)
In this analysis, we focus on events occurring after 1996. This decision is based on information from the NOAA database details available at https://www.ncdc.noaa.gov/stormevents/details.jsp. According to the details, the complete set of Event Types currently in use was developed around this time. Prior to this development, weather events were recorded using only 3 event types, potentially leading to skewed totals for these types. Please note that we will be utilizing the dplyr package for all computations. If you don’t have it installed, please do so before proceeding with the analysis.”
library(dplyr)
dataset1 <- dataset %>% mutate(BGN_DATE = as.character(BGN_DATE)) %>% mutate(BGN_DATE = as.Date(BGN_DATE, "%m/%d/%Y %H:%M:%S")) %>% mutate(BGN_DATE = as.numeric(format(BGN_DATE, "%Y"))) %>% filter(BGN_DATE >= 1996)
While the ‘PROPDMG’ and ‘CROPDMG’ variables may seem numeric, the analysis is significantly impacted by missing information. The auxiliary variables ‘PROPDMGEXP’ and ‘CROPDMGEXP’ indicate whether the numbers in the original columns represent dollar figures in thousands (K), millions (M), or billions (B). An absent or 0 value signifies an accurate dollar figure. To create a unified ‘DMG’ variable, we employ the following function
exp <- function(x,y){
ifelse(y == "K", x*10^3,
ifelse(y == "M", x*10^6,
ifelse(y == "B", x*10^9, ifelse((y == "") | (y == "0"), x, -1000)
)
)
)
}
dataset2 <- dataset1 %>% mutate(total_dmg = exp(PROPDMG, PROPDMGEXP) +exp(CROPDMG, CROPDMGEXP))
At this stage, our anticipation is that the conclusive analysis can be extracted directly from the outcome of the following dplyr pipeline. This pipeline will segment the data by event type and aggregate the sum of all relevant variables for each type:
event_summary <- dataset2 %>% group_by(EVTYPE) %>% summarize(total_fat = sum(FATALITIES), total_inj = sum(INJURIES), total_dmg = sum(total_dmg))
head(event_summary)
## # A tibble: 6 x 4
## EVTYPE total_fat total_inj total_dmg
## <chr> <dbl> <dbl> <dbl>
## 1 " HIGH SURF ADVISORY" 0 0 200000
## 2 " COASTAL FLOOD" 0 0 0
## 3 " FLASH FLOOD" 0 0 50000
## 4 " LIGHTNING" 0 0 0
## 5 " TSTM WIND" 0 0 8100000
## 6 " TSTM WIND (G45)" 0 0 8000
nrow(event_summary)
## [1] 516
There are currently 516 distinct events, and our primary objective is to categorize each of these 516 event types into one of the 48 official categories outlined in the NOAA NWS Documentation (section 2.1.1), accessible at http://www.nws.noaa.gov/directives/sym/pd01016005curr.pdf. In the absence of a perfect assignment, our aim is to capture 95 percent of the relevant variables—namely, fatalities, injuries, and total damage.
In our initial approach, we will introduce a new category label ‘cat’ and assign each event type one of the 48 labels if that label appears as a substring of the ‘EVTYPE’ variable.
official_names <- c("Astronomical Low Tide", "Avalanche", "Blizzard", "Coastal Flood", "Cold/Wind Chill", "Debris Flow", "Dense Fog", "Dense Smoke", "Drought", "Dust Devil", "Dust Storm", "Excessive Heat", "Extreme Cold/Wind Chill", "Flash Flood", "Flood", "Frost/Freeze", "Funnel Cloud", "Freezing Fog", "Hail", "Heat", "Heavy Rain", "Heavy Snow", "High Surf", "High Wind", "Hurricane/Typhoon", "Ice Storm", "Lake-Effect Snow", "Lakeshore Flood", "Lightning", "Marine Hail", "Marine High Wind", "Marine Strong Wind", "Marine Thunderstorm Wind", "Rip Current", "Seiche", "Sleet", "Storm Surge/Tide", "Strong Wind", "Thunderstorm Wind", "Tornado", "Tropical Depression", "Tropical Storm", "Tsunami", "Volcanic Ash", "Waterspout", "Wildfire", "Winter Storm", "Winter Weather")
It’s important to note that some labels are precise refinements of others; for instance, ‘Flash Flood’ refines ‘Flood.’ Therefore, we require a function that will selectively identify only the most specific labels within a given set of labels
which_label <- function(x){
if(length(x) == 1){
return(x)
}
for(i in 1:length(x)){
pattern = x[i]
rest = x[-i]
matches = grep(pattern, rest, ignore.case = TRUE)
if(length(matches) != 0){
return(which_label(rest))
}
}
return(x)
}
Using this function, we construct our comprehensive labeling scheme and embark on our initial endeavor to categorize our event types.
label <- function(x){
y <- rep(0, length(official_names))
for(i in 1:length(official_names)){
pattern = gsub("/", "|", official_names[i])
matches <- grep(pattern, x, ignore.case = TRUE)
if(length(matches) != 0){
y[i] = 1
}
}
if(sum(y) == 1){
official_names[which.max(y)]
}
else{
if(sum(y) > 1){
labels <- official_names[y == 1]
red_labels <- which_label(labels)
if(length(red_labels) == 1){
red_labels
}
else{
"Doubly Named"
}
}
else{
"Still Missing"
}
}
}
first_try <- mutate(event_summary, cat = sapply(event_summary$EVTYPE, label))
sum(first_try$cat == "Still Missing")
## [1] 325
sum(first_try$cat == "Doubly Named")
## [1] 6
While the initial attempt falls short of expectations, further examination exposes typos in event names. To address this, we make an additional effort to approximate matches between event types and official names. The following code implements this approach and provides insight into the remaining work ahead.
library(stringdist)
##
## Attaching package: 'stringdist'
## The following object is masked from 'package:tidyr':
##
## extract
close_enough <- function(x){
dist <- stringdist(tolower(official_names), tolower(x))
rel_dist <- dist/nchar(official_names)
if(min(rel_dist) <= 0.25){
return(official_names[which.min(dist)])
}
else{
return("Still Missing")
}
}
second_try <- first_try %>% mutate(cat = ifelse(cat == "Still Missing", sapply(first_try$EVTYPE, close_enough), cat))
nrow(filter(second_try, cat == "Still Missing"))
## [1] 321
At this juncture, despite our efforts, only four additional events have been successfully classified. We will now assess the current status of variable labeling, examining the fractions that are labeled, doubly counted, or still unaccounted for.
second_try <- mutate(second_try, status = ifelse(cat == "Still Missing", cat, ifelse(cat == "Doubly Named", cat, "Classified")))
so_far <- second_try %>% group_by(status) %>% summarise(total_fat = sum(total_fat), total_inj = sum(total_inj), total_dmg = sum(total_dmg))
so_far
## # A tibble: 3 x 4
## status total_fat total_inj total_dmg
## <chr> <dbl> <dbl> <dbl>
## 1 Classified 8231 52297 392879441940
## 2 Doubly Named 0 0 15320000
## 3 Still Missing 501 5678 8625582170
f <- function(x){x/sum(x)}
so_far_frac <- cbind(so_far[,1], as.data.frame(lapply(so_far[,2:4], f)))
so_far_frac
## status total_fat total_inj total_dmg
## 1 Classified 0.94262483 0.90206123 9.784795e-01
## 2 Doubly Named 0.00000000 0.00000000 3.815498e-05
## 3 Still Missing 0.05737517 0.09793877 2.148230e-02
We are approaching our acceptable threshold of 95 percent for each variable. The only variables that still require classification are the total fatalities (which is nearly complete) and the total injuries. Since the limited number of doubly named events contributes no fatalities, injuries, and only a small portion of the total damage, we will disregard them for our analysis. To determine our next steps, go to examine the ranking of the still unclassified events based on total injuries
still_missing <- second_try %>% filter(cat == "Still Missing") %>% arrange(-total_inj)
still_missing
## # A tibble: 321 x 6
## EVTYPE total_fat total_inj total_dmg cat status
## <chr> <dbl> <dbl> <dbl> <chr> <chr>
## 1 TSTM WIND 241 3629 5031941790 Still Missing Still Miss~
## 2 FOG 60 712 13145500 Still Missing Still Miss~
## 3 WILD/FOREST FIRE 12 545 3108564830 Still Missing Still Miss~
## 4 GLAZE 1 212 60000 Still Missing Still Miss~
## 5 WIND 18 84 2579500 Still Missing Still Miss~
## 6 URBAN/SML STREAM FLD 28 79 66797750 Still Missing Still Miss~
## 7 WINTRY MIX 1 77 10000 Still Missing Still Miss~
## 8 LANDSLIDE 37 52 344595000 Still Missing Still Miss~
## 9 HEAVY SURF 5 40 1340000 Still Missing Still Miss~
## 10 SNOW SQUALL 2 35 30000 Still Missing Still Miss~
## # ... with 311 more rows
Fortuitously, many of these events are evidently classifiable into one of the 48 official names. By recognizing ‘TSTM WIND’ as ‘Thunderstorm Wind,’ ‘FOG’ as ‘Dense Fog,’ ‘WILD/FOREST FIRE’ as ‘Wildfire,’ ‘URBAN/SML STREAM FLD’ as ‘Flood,’ and ‘LANDSLIDE’ as ‘Debris Flow,’ we successfully label 378 out of 501 unclassified fatalities and 5,017 out of 5,678 injuries. Let’s manually incorporate these labels and reevaluate the percentage of each variable that we have now categorized.
names_to_classify <- c("TSTM WIND", "FOG", "WILD/FOREST FIRE", "URBAN/SML STREAM FLD", "LANDSLIDE")
true_names <- c("Thunderstorm Wind", "Dense Fog", "Wildfire", "Flood", "Debris Flow")
manual <- function(x){
index = match(x, names_to_classify)
if(is.na(index)){
return("Still Missing")
}
else{
return(true_names[index])
}
}
third_try <- mutate(second_try, cat = ifelse(cat == "Still Missing", sapply(second_try$EVTYPE, manual), cat))
third_try <- mutate(third_try, status = ifelse(cat == "Still Missing", cat, ifelse(cat == "Doubly Named", cat, "Classified")))
so_far <- third_try %>% group_by(status) %>% summarise(total_fat = sum(total_fat), total_inj = sum(total_inj), total_dmg = sum(total_dmg))
so_far
## # A tibble: 3 x 4
## status total_fat total_inj total_dmg
## <chr> <dbl> <dbl> <dbl>
## 1 Classified 8609 57314 401444486810
## 2 Doubly Named 0 0 15320000
## 3 Still Missing 123 661 60537300
f <- function(x){x/sum(x)}
so_far_frac <- cbind(so_far[,1], as.data.frame(lapply(so_far[,2:4], f)))
so_far_frac
## status total_fat total_inj total_dmg
## 1 Classified 0.98591388 0.98859853 9.998111e-01
## 2 Doubly Named 0.00000000 0.00000000 3.815498e-05
## 3 Still Missing 0.01408612 0.01140147 1.507702e-04
We are nearing our acceptable threshold of 95 percent for each variable. The only variables that still require classification are the total fatalities (which is almost complete) and the total injuries. Given that the limited number of doubly named events contributes no fatalities, injuries, and only a small portion of the total damage, we will disregard them for our analysis. To determine our next steps, let’s examine the ranking of the still unclassified events based on total injuries.
still_missing <- second_try %>% filter(cat == "Still Missing") %>% arrange(-total_inj)
still_missing
## # A tibble: 321 x 6
## EVTYPE total_fat total_inj total_dmg cat status
## <chr> <dbl> <dbl> <dbl> <chr> <chr>
## 1 TSTM WIND 241 3629 5031941790 Still Missing Still Miss~
## 2 FOG 60 712 13145500 Still Missing Still Miss~
## 3 WILD/FOREST FIRE 12 545 3108564830 Still Missing Still Miss~
## 4 GLAZE 1 212 60000 Still Missing Still Miss~
## 5 WIND 18 84 2579500 Still Missing Still Miss~
## 6 URBAN/SML STREAM FLD 28 79 66797750 Still Missing Still Miss~
## 7 WINTRY MIX 1 77 10000 Still Missing Still Miss~
## 8 LANDSLIDE 37 52 344595000 Still Missing Still Miss~
## 9 HEAVY SURF 5 40 1340000 Still Missing Still Miss~
## 10 SNOW SQUALL 2 35 30000 Still Missing Still Miss~
## # ... with 311 more rows
Fortunately, many of these events can be easily categorized into one of the 48 official names. By identifying ‘TSTM WIND’ as ‘Thunderstorm Wind,’ ‘FOG’ as ‘Dense Fog,’ ‘WILD/FOREST FIRE’ as ‘Wildfire,’ ‘URBAN/SML STREAM FLD’ as ‘Flood,’ and ‘LANDSLIDE’ as ‘Debris Flow,’ we successfully assign labels to 378 out of 501 unclassified fatalities and 5,017 out of 5,678 injuries. Let’s manually incorporate these labels and reassess the percentage of each variable that we have now categorized.
names_to_classify <- c("TSTM WIND", "FOG", "WILD/FOREST FIRE", "URBAN/SML STREAM FLD", "LANDSLIDE")
true_names <- c("Thunderstorm Wind", "Dense Fog", "Wildfire", "Flood", "Debris Flow")
manual <- function(x){
index = match(x, names_to_classify)
if(is.na(index)){
return("Still Missing")
}
else{
return(true_names[index])
}
}
third_try <- mutate(second_try, cat = ifelse(cat == "Still Missing", sapply(second_try$EVTYPE, manual), cat))
third_try <- mutate(third_try, status = ifelse(cat == "Still Missing", cat, ifelse(cat == "Doubly Named", cat, "Classified")))
so_far <- third_try %>% group_by(status) %>% summarise(total_fat = sum(total_fat), total_inj = sum(total_inj), total_dmg = sum(total_dmg))
so_far
## # A tibble: 3 x 4
## status total_fat total_inj total_dmg
## <chr> <dbl> <dbl> <dbl>
## 1 Classified 8609 57314 401444486810
## 2 Doubly Named 0 0 15320000
## 3 Still Missing 123 661 60537300
f <- function(x){x/sum(x)}
so_far_frac <- cbind(so_far[,1], as.data.frame(lapply(so_far[,2:4], f)))
so_far_frac
## status total_fat total_inj total_dmg
## 1 Classified 0.98591388 0.98859853 9.998111e-01
## 2 Doubly Named 0.00000000 0.00000000 3.815498e-05
## 3 Still Missing 0.01408612 0.01140147 1.507702e-04
With the successful categorization of these five events, we have now explained 98 percent of all three variables, aligning wth our initial objectives. Let’s now summarize based on the real names, represented by the ‘cat’ variable.”
true_event_summary <- third_try %>% group_by(cat) %>% summarize(total_fat = sum(total_fat), total_inj = sum(total_inj), total_dmg = sum(total_dmg))
true_event_summary <- arrange(true_event_summary, -total_dmg)
true_event_summary
## # A tibble: 49 x 4
## cat total_fat total_inj total_dmg
## <chr> <dbl> <dbl> <dbl>
## 1 Flood 444 6839 149173965700
## 2 Hurricane/Typhoon 125 1328 87068996810
## 3 Storm Surge/Tide 13 42 47845004000
## 4 Tornado 1511 20667 24900370720
## 5 Hail 12 818 17201087620
## 6 Flash Flood 887 1674 16557160610
## 7 Drought 0 4 14413667000
## 8 Thunderstorm Wind 372 5029 8812927230
## 9 Tropical Storm 57 338 8320186550
## 10 Wildfire 87 1456 8162704630
## # ... with 39 more rows
We found that a small subset of event types, whether in terms of human life or property, is responsible for the majority of all losses. In terms of human life, extreme heat and tornadoes emerge as the two most lethal severe weather events, collectively contributing to 40 percent of all fatalities
library(ggplot2)
# Graph fatalities
graph_fat <- ggplot(head(arrange(true_event_summary, desc(total_fat)), 10), aes(x = reorder(cat, total_fat), y = total_fat, fill = factor(rank(desc(total_fat)))))+
geom_bar(stat = "identity")+
scale_fill_brewer(palette = "Blues",direction = -1)+
labs(title = "Top 10 Event Types by Fatalities",
x = "Event Type",
y = "Total Fatalities")+ theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Graph injured
graph_inj <- ggplot(head(arrange(true_event_summary, desc(total_inj)), 10), aes(x = reorder(cat, total_inj), y = total_inj, fill = factor(rank(desc(total_inj)))))+
geom_bar(stat = "identity")+
scale_fill_brewer(palette = "Greens",direction = -1)+
labs(title = "Top 10 Event Types by Injuries",
x = "Event Type",
y = "Total Injuries")+
theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Graph economy
graph_dmg <- ggplot(head(arrange(true_event_summary, desc(total_dmg)), 5), aes(x = reorder(cat, total_dmg), y = total_dmg, fill = factor(rank(desc(total_dmg)))))+
geom_bar(stat = "identity")+
scale_fill_brewer(palette = "Reds",direction = -1)+
labs(title = "Top 10 Event Types by Total Damage",
x = "Event Type",
y = "Total Damage in billion dollar")+
theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Afficher les graphiques
print(graph_fat)
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Blues is 9
## Returning the palette you asked for with that many colors
print(graph_inj)
print(graph_dmg)