getwd()
## [1] "C:/Users/deloz/OneDrive/Documentos/R/week4"
setwd("C:/Users/deloz/OneDrive/Documentos/R")

####Loading the Libraries and Preparong R Enviroment

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(ggplot2)
library(grid)
library(plyr)
## ------------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## ------------------------------------------------------------------------------
## 
## Attaching package: 'plyr'
## 
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## 
## The following object is masked from 'package:purrr':
## 
##     compact
library(gridExtra)
## 
## Attaching package: 'gridExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
library(readr)
library(readxl)

Session Info

sessionInfo()
## R version 4.4.0 (2024-04-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 22631)
## 
## Matrix products: default
## 
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8 
## [2] LC_CTYPE=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## time zone: America/Denver
## tzcode source: internal
## 
## attached base packages:
## [1] grid      stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] readxl_1.4.3    gridExtra_2.3   plyr_1.8.9      lubridate_1.9.3
##  [5] forcats_1.0.0   stringr_1.5.1   dplyr_1.1.4     purrr_1.0.2    
##  [9] readr_2.1.5     tidyr_1.3.1     tibble_3.2.1    ggplot2_3.5.1  
## [13] tidyverse_2.0.0
## 
## loaded via a namespace (and not attached):
##  [1] gtable_0.3.5      jsonlite_1.8.8    compiler_4.4.0    Rcpp_1.0.12      
##  [5] tidyselect_1.2.1  jquerylib_0.1.4   scales_1.3.0      yaml_2.3.8       
##  [9] fastmap_1.1.1     R6_2.5.1          generics_0.1.3    knitr_1.46       
## [13] munsell_0.5.1     bslib_0.7.0       pillar_1.9.0      tzdb_0.4.0       
## [17] rlang_1.1.3       utf8_1.2.4        stringi_1.8.4     cachem_1.0.8     
## [21] xfun_0.43         sass_0.4.9        timechange_0.3.0  cli_3.6.2        
## [25] withr_3.0.0       magrittr_2.0.3    digest_0.6.35     rstudioapi_0.16.0
## [29] hms_1.1.3         lifecycle_1.0.4   vctrs_0.6.5       evaluate_0.23    
## [33] glue_1.7.0        cellranger_1.1.0  fansi_1.0.6       colorspace_2.1-0 
## [37] rmarkdown_2.26    tools_4.4.0       pkgconfig_2.0.3   htmltools_0.5.8.1

SYNOPSIS

This analysis aims to assess the impact of the top 10 weather events in the United States on public health and the economy, using data from the National Oceanic and Atmospheric Administration (NOAA) storm database. The dataset covers events from 1950 onwards, and the analysis focuses on fatalities, injuries, property damages and crop damages caused by these events.

Reading the data

if(!exists("storm_data")) 
  {storm_data <- read.csv("repdata_data_StormData (1).csv")}
dim(storm_data)
## [1] 902297     37

Define the variables of interest

Health variables: FATALITIES: approx. number of deaths INJURIES: approx. number of injuries Economic variables: PROPDMG: approx. property damags PROPDMGEXP: the units for property damage value CROPDMG: approx. crop damages CROPDMGEXP: the units for crop damage value Events - target variable: EVTYPE: weather event (Tornados, Wind, Snow, Flood, etc..)

vars <- c( "EVTYPE", "FATALITIES", "INJURIES", "PROPDMG", "PROPDMGEXP", "CROPDMG", "CROPDMGEXP")

Cleaning the Data

storm_data_trim <- storm_data[, vars]
tail(storm_data_trim)
##                EVTYPE FATALITIES INJURIES PROPDMG PROPDMGEXP CROPDMG CROPDMGEXP
## 902292 WINTER WEATHER          0        0       0          K       0          K
## 902293      HIGH WIND          0        0       0          K       0          K
## 902294      HIGH WIND          0        0       0          K       0          K
## 902295      HIGH WIND          0        0       0          K       0          K
## 902296       BLIZZARD          0        0       0          K       0          K
## 902297     HEAVY SNOW          0        0       0          K       0          K

Perform a check for missing values for all variables of interest:

Fatalities

sum(is.na(storm_data_trim$FATALITIES))
## [1] 0

Injuries

sum(is.na(storm_data_trim$INJURIES))
## [1] 0

Property Damages

sum(is.na(storm_data_trim$PROPDMG))
## [1] 0

Crop Damages

sum(is.na(storm_data_trim$CROPDMG))
## [1] 0
sum(is.na(storm_data_trim$PROPDMGEXP))
## [1] 0
sum(is.na(storm_data_trim$CROPDMGEXP))
## [1] 0

Event types

Sort and filter for the first 10 most common event types:

sort(table(storm_data_trim$EVTYPE), decreasing = TRUE)[1:10]
## 
##               HAIL          TSTM WIND  THUNDERSTORM WIND            TORNADO 
##             288661             219940              82563              60652 
##        FLASH FLOOD              FLOOD THUNDERSTORM WINDS          HIGH WIND 
##              54277              25326              20843              20212 
##          LIGHTNING         HEAVY SNOW 
##              15754              15708

Create a new variable EVENT to transform variable EVTYPE into groups:

storm_data_trim$EVENT <- "OTHER"
storm_data_trim$EVENT[grep("HAIL", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "HAIL"
storm_data_trim$EVENT[grep("HEAT", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "HEAT"
storm_data_trim$EVENT[grep("FLOOD", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "FLOOD"
storm_data_trim$EVENT[grep("WIND", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "WIND"
storm_data_trim$EVENT[grep("STORM", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "STORM"
storm_data_trim$EVENT[grep("SNOW", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "SNOW"
storm_data_trim$EVENT[grep("TORNADO", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "TORNADO"
storm_data_trim$EVENT[grep("WINTER", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "WINTER"
storm_data_trim$EVENT[grep("RAIN", storm_data_trim$EVTYPE, ignore.case = TRUE)] <- "RAIN"


sort(table(storm_data_trim$EVENT), decreasing = TRUE)
## 
##    HAIL    WIND   STORM   FLOOD TORNADO   OTHER  WINTER    SNOW    RAIN    HEAT 
##  289270  255362  113156   82686   60700   48970   19604   17660   12241    2648

Which types of events have the greatest economic consequences?

sort(table(storm_data_trim$PROPDMGEXP), decreasing = TRUE)[1:10]
## 
##             K      M      0      B      5      1      2      ?      m 
## 465934 424665  11330    216     40     28     25     13      8      7

###Convert units to dollars: * K or k equals 1,000 dollars (10^3), * M or m equals 1,000,000 dollars (10^6), * B or b equals 1,000,000,000 dollars (10^9), * the rest will be considered as dollars.

storm_data_trim$PROPDMGEXP <- as.character(storm_data_trim$PROPDMGEXP)
storm_data_trim$PROPDMGEXP[is.na(storm_data_trim$PROPDMGEXP)] <- 0
storm_data_trim$PROPDMGEXP[!grepl("K|M|B", storm_data_trim$PROPDMGEXP, ignore.case = TRUE)] <- 0 
storm_data_trim$PROPDMGEXP[grep("K", storm_data_trim$PROPDMGEXP, ignore.case = TRUE)] <- "3"
storm_data_trim$PROPDMGEXP[grep("M", storm_data_trim$PROPDMGEXP, ignore.case = TRUE)] <- "6"
storm_data_trim$PROPDMGEXP[grep("B", storm_data_trim$PROPDMGEXP, ignore.case = TRUE)] <- "9"
storm_data_trim$PROPDMGEXP <- as.numeric(as.character(storm_data_trim$PROPDMGEXP))
storm_data_trim$property.damage <- storm_data_trim$PROPDMG * 10^storm_data_trim$PROPDMGEXP

storm_data_trim$CROPDMGEXP <- as.character(storm_data_trim$CROPDMGEXP)
storm_data_trim$CROPDMGEXP[is.na(storm_data_trim$CROPDMGEXP)] <- 0 
storm_data_trim$CROPDMGEXP[!grepl("K|M|B", storm_data_trim$CROPDMGEXP, ignore.case = TRUE)] <- 0 
storm_data_trim$CROPDMGEXP[grep("K", storm_data_trim$CROPDMGEXP, ignore.case = TRUE)] <- "3"
storm_data_trim$CROPDMGEXP[grep("M", storm_data_trim$CROPDMGEXP, ignore.case = TRUE)] <- "6"
storm_data_trim$CROPDMGEXP[grep("B", storm_data_trim$CROPDMGEXP, ignore.case = TRUE)] <- "9"
storm_data_trim$CROPDMGEXP <- as.numeric(as.character(storm_data_trim$CROPDMGEXP))
storm_data_trim$crop.damage <- storm_data_trim$CROPDMG * 10^storm_data_trim$CROPDMGEXP

largest property damage:

sort(table(storm_data_trim$property.damage), decreasing = TRUE)[1:10]
## 
##      0   5000  10000   1000   2000  25000  50000   3000  20000  15000 
## 663123  31731  21787  17544  17186  17104  13596  10364   9179   8617

largest crop damage:

sort(table(storm_data_trim$crop.damage), decreasing = TRUE)[1:10]
## 
##      0   5000  10000  50000  1e+05   1000   2000  25000  20000  5e+05 
## 880198   4097   2349   1984   1233    956    951    830    758    721

###Analysis

Public Health Events

agg.fatalites.and.injuries <- d_ply(storm_data_trim, .(EVENT), summarize, Total = sum(FATALITIES + INJURIES,  na.rm = TRUE))
agg.fatalites.and.injuries$type <- "fatalities and injuries"
  
agg.fatalities <- ddply(storm_data_trim, .(EVENT), summarize, Total = sum(FATALITIES, na.rm = TRUE))
agg.fatalities$type <- "fatalities"

agg.injuries <- ddply(storm_data_trim, .(EVENT), summarize, Total = sum(INJURIES, na.rm = TRUE))
agg.injuries$type <- "injuries"

agg.health <- rbind(agg.fatalities, agg.injuries)

health.by.event <- join (agg.fatalities, agg.injuries, by="EVENT", type="inner")
health.by.event
##      EVENT Total       type Total     type
## 1    FLOOD  1524 fatalities  8602 injuries
## 2     HAIL    15 fatalities  1371 injuries
## 3     HEAT  3138 fatalities  9224 injuries
## 4    OTHER  2626 fatalities 12224 injuries
## 5     RAIN   114 fatalities   305 injuries
## 6     SNOW   164 fatalities  1164 injuries
## 7    STORM   416 fatalities  5339 injuries
## 8  TORNADO  5661 fatalities 91407 injuries
## 9     WIND  1209 fatalities  9001 injuries
## 10  WINTER   278 fatalities  1891 injuries

Economic Events

agg.propdmg.and.cropdmg <- ddply(storm_data_trim, .(EVENT), summarize, Total = sum(property.damage + crop.damage,  na.rm = TRUE))
agg.propdmg.and.cropdmg$type <- "property and crop damage"

agg.prop <- ddply(storm_data_trim, .(EVENT), summarize, Total = sum(property.damage, na.rm = TRUE))
agg.prop$type <- "property"

agg.crop <- ddply(storm_data_trim, .(EVENT), summarize, Total = sum(crop.damage, na.rm = TRUE))
agg.crop$type <- "crop"

agg.economic <- rbind(agg.prop, agg.crop)

economic.by.event <- join (agg.prop, agg.crop, by="EVENT", type="inner")
economic.by.event
##      EVENT        Total     type       Total type
## 1    FLOOD 167502193929 property 12266906100 crop
## 2     HAIL  15733043048 property  3046837473 crop
## 3     HEAT     20325750 property   904469280 crop
## 4    OTHER  97246712337 property 23588880870 crop
## 5     RAIN   3270230192 property   919315800 crop
## 6     SNOW   1024169752 property   134683100 crop
## 7    STORM  66304415393 property  6374474888 crop
## 8  TORNADO  58593098029 property   417461520 crop
## 9     WIND  10847166618 property  1403719150 crop
## 10  WINTER   6777295251 property    47444000 crop

Results: Across the United States, which types of events (as indicated in the EVTYPE variable) are most harmful with respect to population health?

The most harmful event with respect to population health is a TORNAD0.

agg.health$EVENT <- as.factor(agg.health$EVENT)

health.plot <- ggplot(agg.health, aes(x = EVENT, y = Total, fill = type)) + geom_bar(stat = "identity") +
  coord_flip() +
  xlab("Event Type") + 
  ylab("Total number of health impact") +
  ggtitle("Weather event types impact on public health") +
  theme(plot.title = element_text(hjust = 0.5))
print(health.plot)  

###Across the United States, which types of events have the greatest economic consequences?

The event with the greatest economic consequences is a FLOOD.

agg.economic$EVENT <- as.factor(agg.economic$EVENT)

economic.plot <- ggplot(agg.economic, aes(x = EVENT, y = Total, fill = type)) + geom_bar(stat = "identity") +
  coord_flip() +
  xlab("Event Type") + 
  ylab("Total damage in dollars") +
  ggtitle("Weather event types impact on property and crop damage") +
  theme(plot.title = element_text(hjust = 0.5))
print(economic.plot) 

Conclusion

The findings of this examination underscore the significant influence weather phenomena exert on both public health and the economy within the United States. Discerning the particular kinds of occurrences responsible for the greatest damage can guide disaster readiness and resource distribution endeavors, enhancing community safeguarding and mitigating the adverse repercussions of such incidents.