-
Notifications
You must be signed in to change notification settings - Fork 0
/
.Rhistory
512 lines (512 loc) · 25.4 KB
/
.Rhistory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
mean_Tor=(all_tor%>%summarize(Tornados=mean(Tornados)))$Tornados
mean_Tor
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
as.numeric(colSums(all_tor)[[2]])
colSums(all_tor)[[2,1]]
colSums(all_tor)[[2]][2]
colSums(all_tor)[[2]][1]
colSums(all_tor)[[2]]
colSums(all_tor)[[2]][1],
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
num=as.numeric(colSums(all_tor)[[2]])
print(num)
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
shiny::runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
colMeans(all_tor)
all_tor
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
runApp('Google Drive/Tornado_US_Coursera/Tornado_US')
date: October 2016
autosize: true
# Chunk 1
library(ggplot2)
library(ggmap)
library(dplyr)
tornados_clean = read.csv('tornados_clean_10-16.csv')
names(tornados_clean)
# Chunk 2
all_tor=tornados_clean%>%group_by(YEAR)%>%summarize(Tornados=n())
summary(all_tor)
# Chunk 3
mean_Tor=(all_tor%>%summarize(Tornados=mean(Tornados)))$Tornados
N_tor=ggplot(all_tor,aes(x = YEAR ,y = Tornados)) +
geom_bar(stat="identity", colour="blue", fill = "darkblue") + guides(fill=FALSE)+
xlab("YEAR") + ylab("No. of Tornados") +
scale_y_continuous( limits = c(0,2100)) +
geom_hline(yintercept = mean_Tor)
N_tor
# Chunk 4
tor_DT=tornados_clean%>%filter(YEAR>="2015")
tor_DT=tor_DT%>%filter(YEAR<="2016")
# Upload the US map:
coordS=c(-160,40,-40,45)
getTheMap <- suppressMessages(get_map(location = coordS, zoom = 4, source = 'google', maptype = "terrain" ))
# Add the tornados to the map:
mapDT_All = distinct(tor_DT%>%dplyr::select(YEAR,BEGIN_LON, BEGIN_LAT))
tornados_US = suppressMessages(ggmap(getTheMap) +
geom_point(aes(x=BEGIN_LON, y=BEGIN_LAT),
data = mapDT_All,
size = 1,
colour="blue",
alpha=.5))
tornados_US
# Chunk 1
library(ggplot2)
library(ggmap)
library(dplyr)
tornados_clean = read.csv('tornados_clean_10-16.csv')
names(tornados_clean)
# Chunk 2
all_tor=tornados_clean%>%group_by(YEAR)%>%summarize(Tornados=n())
summary(all_tor)
# Chunk 3
mean_Tor=(all_tor%>%summarize(Tornados=mean(Tornados)))$Tornados
N_tor=ggplot(all_tor,aes(x = YEAR ,y = Tornados)) +
geom_bar(stat="identity", colour="blue", fill = "darkblue") + guides(fill=FALSE)+
xlab("YEAR") + ylab("No. of Tornados") +
scale_y_continuous( limits = c(0,2100)) +
geom_hline(yintercept = mean_Tor)
N_tor
# Chunk 4
tor_DT=tornados_clean%>%filter(YEAR>="2015")
tor_DT=tor_DT%>%filter(YEAR<="2016")
# Upload the US map:
coordS=c(-160,40,-40,45)
getTheMap <- suppressMessages(get_map(location = coordS, zoom = 4, source = 'google', maptype = "terrain" ))
# Add the tornados to the map:
mapDT_All = distinct(tor_DT%>%dplyr::select(YEAR,BEGIN_LON, BEGIN_LAT))
tornados_US = suppressMessages(ggmap(getTheMap) +
geom_point(aes(x=BEGIN_LON, y=BEGIN_LAT),
data = mapDT_All,
size = 1,
colour="blue",
alpha=.5))
tornados_US
library(XML)
library(R.utils)
library(XML)
library(R.utils)
library(plyr)
library(dplyr)
library(ggplot2)
library(rgdal)
library(rgeos)
library(data.table)
library(tidyr)
library(ggmap)
library(scales)
library(dismo) # this package masks some of dplyr functions.
library(highcharter)
library(htmlwidgets)
library(viridisLite)
setwd("/Users/jpinzon/Google Drive/git/TORNADOS_USA")
dir()
initial.dir<-getwd()
dir()
tornados = read.csv('tornados_10-16.csv')
initial.dir<-getwd()
tornados_clean = read.csv('tornados_clean_10-16.csv')
cat("According to NOAA, there has been",nrow(tornados_clean)," tornados reported in the US since 1951")
tor_Year = tornados_clean%>%group_by(YEAR)%>%dplyr::summarise(total.count=n())
library(XML)
library(R.utils)
library(plyr)
library(dplyr)
library(ggplot2)
library(rgdal)
library(rgeos)
library(data.table)
library(tidyr)
library(ggmap)
library(scales)
library(dismo) # this package masks some of dplyr functions.
library(highcharter)
library(htmlwidgets)
library(viridisLite)
########################## DOWNLOAD AND LOAD DATA INTO R ###################################
# The data is from NOAA.
# The files can be found @
# http://www1.ncdc.noaa.gov/pub/data/swdi/stormevents/csvfiles/
# The batch download step is adapted from
# http://www.guru-gis.net/batch-download-files-using-r/
# Set the working directory
initial.dir<-getwd()
cat("According to NOAA, there has been",nrow(tornados_clean)," tornados reported in the US since 1951. With an average of", ave_tor,"tornados per year.")
tor_Year = tornados_clean%>%group_by(YEAR)%>%dplyr::summarise(total.count=n())
tor_Year
as.data.table(tor_Year)
# Average tonados/year
ave_tor= as.integer(tor_Year%>%summarise(average=mean(total.count, na.rm=T)))
cat("According to NOAA, there has been",nrow(tornados_clean)," tornados reported in the US since 1951. With an average of", ave_tor,"tornados per year.")
# Plot Year vs. No. of Tornados
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2015)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue")
# Calculate the total number of tornados per scale:
# The Enhance F-scale (EF) was adopted in 2007.
# See this site for additional explanations: http://www.spc.noaa.gov/faq/tornado/ef-scale.html
tornados_clean%>%group_by(TOR_F_SCALE)%>%dplyr::summarise(total.count=n())
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2016)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue")
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2016)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue", label_both(c("Average")))
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2016)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue"))
geom_hline(yintercept = ave_tor, col ="blue")))
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2016)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue")))
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2016)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue")
cat("According to NOAA, there has been",nrow(tornados_clean)," tornados reported in the US since 1951")
# Tornados per year
tor_Year = tornados_clean%>%group_by(YEAR)%>%dplyr::summarise(total.count=n())
as.data.table(tor_Year)
# Average tonados/year
ave_tor= as.integer(tor_Year%>%summarise(average=mean(total.count, na.rm=T)))
cat("According to NOAA, there has been",nrow(tornados_clean)," tornados reported in the US since 1951. With an average of", ave_tor,"tornados per year.")
# Plot Year vs. No. of Tornados
ggplot(tor_Year, aes(YEAR, total.count)) + geom_line()+
ggtitle("Tornados in the US (1951-2016)") +
xlab("YEAR") + ylab("No. of Tornados") +
geom_hline(yintercept = ave_tor, col ="blue")
# Calculate the total number of tornados per scale:
# The Enhance F-scale (EF) was adopted in 2007.
# See this site for additional explanations: http://www.spc.noaa.gov/faq/tornado/ef-scale.html
tornados_clean%>%group_by(TOR_F_SCALE)%>%dplyr::summarise(total.count=n())
# For a particular year
# Change the year variable to the desired value (data base goes from 1951 to 2015)
year = 2014
tornados_clean %>% filter(YEAR == year)%>% group_by(TOR_F_SCALE)%>%dplyr::summarise(total.count=n())
# Combining columns
# Create a vector with the columns you want to combine:
# Add variables as you which. This examples is for Year and Scale
tor_cols <- c("YEAR", "TOR_F_SCALE")
# Convert the vector into a list of symbols
col_com <- lapply(tor_cols, as.symbol)
# Determine the total number of tornados for the combination of Year and Scale
tor_scale = tornados_clean %>%group_by_(.dots=col_com) %>%dplyr::summarise(n = n())
tor_scale
# The plot. It is not very informative
ggplot(all_tor,aes(x = YEAR ,y = count)) +
geom_bar(stat="identity") + guides(fill=FALSE)+
xlab("") + ylab("No. of Tornados")
# It is probably better to run one for a particular year.
year2="1965"
tor_scale_year = tornados_clean%>%filter(YEAR==year2)%>%group_by_(.dots=col_com)%>%dplyr::summarise(n=n())
ggplot(tor_scale_year,aes(x = TOR_F_SCALE,y = n)) +
geom_bar(stat="identity", aes(fill = TOR_F_SCALE),position = "dodge")+ guides(fill=FALSE) +
xlab("") + ylab("No. of Tornados")
############################## NUMBER OF DEATHS ############################
### Using dplyr - THIS CAN ALSO BE DONE WITH data.table
# Create a new data.frame and add a colum with the total number deaths
# direct and indirect (Not clear what the difference is and no explanation in original)
tor_DT = tornados_clean %>% mutate(DEATHS = tornados_clean$DEATHS_DIRECT + tornados_clean$DEATHS_INDIRECT)
# Make a column with the month as number (1 through 12) not letters (January to December):
# This will make ploting easier
tor_DT<-tor_DT%>%mutate(MONTH = substr(tor_DT$BEGIN_YEARMONTH, nchar(tor_DT$BEGIN_YEARMONTH)-1, nchar(tor_DT$BEGIN_YEARMONTH)))
# id unique columns and melt them by the measures DEATH_TYPE
# The package dismo masks the function select therefore it will not work. USE dplyr::select
t1 = distinct(tor_DT%>%dplyr::select(STATE, YEAR, MONTH, MONTH_NAME, DEATHS, DEATHS_DIRECT, DEATHS_INDIRECT)%>%gather(DEATH_TYPE, value, DEATHS:DEATHS_INDIRECT))
#PLOTING THE NUMBER OF DEATHS PER DECADE IN THE USA:
# CREATE A NEW COLUM WITH THE DECADE:
t1=t1%>% mutate(DECADE = ifelse(YEAR<=1959 & YEAR>=1950, 1950, ifelse(YEAR<=1969 & YEAR>=1960,1960,ifelse(YEAR<=1979 & YEAR>=1970,1970,ifelse(YEAR<=1989 & YEAR>=1980,1980,ifelse(YEAR<=1999 & YEAR>=1990,1990,ifelse(YEAR<=2009 & YEAR>=2000,2000, 2010)))))))
# Calculate sum, max, min, and mean deaths per decade
s_deaths = t1[t1$DEATH_TYPE!="DEATHS",]%>%dplyr::select(DEATH_TYPE, DECADE, value)%>%group_by(DEATH_TYPE, DECADE)%>%summarise_each(funs(mean, sum, max, min))
#PLOT
ggplot(s_deaths, aes(x=factor(DECADE), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Total number of deaths caused by \n TORNADOS in the USA per DECADE") +
xlab("DECADE") + ylab("No. of DEATHS")
# Montlhy number of DEATHS caused by Tordados in the USA per decade
ggplot(t1[t1$DEATH_TYPE!="DEATHS",], aes(x=factor(MONTH), y=value, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
facet_wrap(~DECADE) +
ggtitle("Average monthly Tornado-related \n deaths in the USA per decade") +
xlab("Month") + ylab("No. of DEATHS")
# AVERAGE MONTHTLY DEATH
s_month_deaths = t1[t1$DEATH_TYPE!="DEATHS",]%>%dplyr::select(DEATH_TYPE, MONTH, value)%>%group_by(DEATH_TYPE, MONTH)%>%summarise_each(funs(mean, sum, max, min))
ggplot(s_deaths, aes(x=factor(DECADE), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Total number of deaths caused by \n TORNADOS in the USA per DECADE") +
xlab("DECADE") + ylab("No. of DEATHS")
# Montlhy number of DEATHS caused by Tordados in the USA per decade
ggplot(t1[t1$DEATH_TYPE!="DEATHS",], aes(x=factor(MONTH), y=value, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
facet_wrap(~DECADE) +
ggtitle("Average monthly Tornado-related \n deaths in the USA per decade") +
xlab("Month") + ylab("No. of DEATHS")
# AVERAGE MONTHTLY DEATH
s_month_deaths = t1[t1$DEATH_TYPE!="DEATHS",]%>%dplyr::select(DEATH_TYPE, MONTH, value)%>%group_by(DEATH_TYPE, MONTH)%>%summarise_each(funs(mean, sum, max, min))
# Montlhy average DEATHS caused by Tordados in the USA
ggplot(s_month_deaths[s_month_deaths$DEATH_TYPE!="DEATHS",], aes(x=factor(MONTH), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Average monthly Tornado-related \n deaths in the USA") +
xlab("Month") + ylab("No. of DEATHS")
ggplot(s_state[s_state$DEATH_TYPE!="DEATHS",], aes(x=factor(STATE), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Average monthly Tornado-related \n deaths per State in the USA") +
xlab("STATE") + ylab("No. of DEATHS")+
coord_flip()
ggplot(t1[t1$DEATH_TYPE!="DEATHS",], aes(x=factor(MONTH), y=value, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
facet_wrap(~DECADE) +
ggtitle("Average monthly Tornado-related \n deaths in the USA per decade") +
xlab("Month") + ylab("No. of DEATHS")
# AVERAGE MONTHTLY DEATH
s_month_deaths = t1[t1$DEATH_TYPE!="DEATHS",]%>%dplyr::select(DEATH_TYPE, MONTH, value)%>%group_by(DEATH_TYPE, MONTH)%>%summarise_each(funs(mean, sum, max, min))
# Montlhy average DEATHS caused by Tordados in the USA
ggplot(s_month_deaths[s_month_deaths$DEATH_TYPE!="DEATHS",], aes(x=factor(MONTH), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Average monthly Tornado-related \n deaths in the USA") +
xlab("Month") + ylab("No. of DEATHS")
# DEATHS PER STATE
s_state = t1[t1$DEATH_TYPE!="DEATHS",]%>%dplyr::select(DEATH_TYPE, STATE, value)%>%group_by(DEATH_TYPE, STATE)%>%summarise_each(funs(mean, sum, max, min))
# State(s) with maximum/minimum number of DIRECT_DEATHS:
maxST_direct = as.character(s_state%>%filter(DEATH_TYPE=="DEATHS_DIRECT")%>%filter(sum==max(sum))%>%dplyr::select(STATE)%>%collect %>% .[["STATE"]])
maxNo_direct =unique(as.character(s_state%>%filter(DEATH_TYPE=="DEATHS_DIRECT")%>%filter(sum==max(sum))%>%dplyr::select(sum)%>%collect %>% .[["sum"]]))
minST_direct = as.character(s_state%>%filter(DEATH_TYPE=="DEATHS_DIRECT")%>%filter(sum==min(sum))%>%dplyr::select(STATE)%>%collect %>% .[["STATE"]])
minNo_direct =unique(as.character(s_state%>%filter(DEATH_TYPE=="DEATHS_DIRECT")%>%filter(sum==min(sum))%>%dplyr::select(sum)%>%collect %>% .[["sum"]]))
cat("The state(s) with higher mortalities (direct deaths) due to Tornados is/are", maxST_direct, "with", maxNo_direct,"deaths.")
cat("The state(s) with lower mortalities (direct deaths) due to Tornados is/are",minST_direct, "with",minNo_direct,"deaths.")
# Montlhy average DEATHS caused by Tordados in the USA
ggplot(s_state[s_state$DEATH_TYPE!="DEATHS",], aes(x=factor(STATE), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Average monthly Tornado-related \n deaths per State in the USA") +
xlab("STATE") + ylab("No. of DEATHS")+
coord_flip()
ggplot(s_state[s_state$DEATH_TYPE!="DEATHS",], aes(x=reorder(STATE,sum), y=sum, fill = DEATH_TYPE )) +
geom_bar(stat="identity") +
ggtitle("Average monthly Tornado-related \n deaths per State in the USA") +
xlab("STATE") + ylab("No. of DEATHS")+
coord_flip()
###################### CREATE MAPS LOCALIZING THE TORNADOS ####################################:
# Upload the US MAP
getTheMap <- suppressMessages(get_map(location = 'united states', zoom = 4, source = 'google'))
# Plot the location of tornados for a particular year (Change the year)
# Select the data for the map
# Adjust the filter option at the end for another year:
mapDT_year <- distinct(tor_DT%>%dplyr::select(YEAR,BEGIN_LON, BEGIN_LAT, DEATHS)%>%filter(YEAR==2015))
# Create a map with the tornados for that year
tor_one_year <- suppressMessages(ggmap(getTheMap) +
geom_point(aes(x=BEGIN_LON, y=BEGIN_LAT),
data = mapDT_year,
size= mapDT_year $DEATHS*5, # size is proportional to the number. Their scale can be changed here.
colour="red",
alpha=.5)+
ggtitle("Tornado-related deaths in US (2015)")) # CHANGE YEAR HERE!!
tor_one_year
mapDT_All <- distinct(tor_DT%>%dplyr::select(YEAR,BEGIN_LON, BEGIN_LAT, DEATHS))
tornados_US_50 <- suppressMessages(ggmap(getTheMap) +
geom_point(aes(x=BEGIN_LON, y=BEGIN_LAT),
data = mapDT_All,
size=mapDT_All$DEATHS*.1,
colour="red",
alpha=.5) +
ggtitle("Tornado-related deaths in the US 1950-2015"))
tornados_US_50
################# PLOT TORNADOS AND RELATED DEATHS ON MAP OF AN AREA OF INTEREST ##########
# Isolating the coordinates for all tornados in the dataset
locationCoords = tor_DT%>%dplyr::select(originalPlace=X, lon=BEGIN_LON, lat=BEGIN_LAT)
head(tor_DT)
# Coordinates for the City of Interest
# Enter the name of the city or location
city_of_interest = "Tulsa, OK"
cityOI = mutate(suppressMessages(geocode(city_of_interest)), originalPlace = (city_of_interest[1]))
cityOI = cityOI%>%dplyr::select(originalPlace, lon=longitude, lat=latitude)
Sorting the locations closer to the city of interest (cityOI)
deg2rad <- function(deg) return(deg*pi/180)
gcd.slc <- function(long1, lat1, long2, lat2) {
long1 <- deg2rad(long1)
lat1 <- deg2rad(lat1)
long2 <- deg2rad(long2)
lat2 <- deg2rad(lat2)
R <- 6371 # Earth mean radius [km]
d <- acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2) * cos(long2-long1)) * R
d <- d*0.621371 #in miles
return(d) # Distance in miles
}
distance <- gcd.slc(cityOI$lon, cityOI$lat, locationCoords$lon, locationCoords$lat)
distance_matrix <- which( distance <= 75 ) # 75 miles from the center
Area_COI = rbind((filter(locationCoords, originalPlace %in% distance_matrix)),cityOI)
cityMap <- gmap(city_of_interest, zoom=8, scale = 2)
plot(cityMap)
coordinates(cityOI) <- ~ lon + lat
projection(cityOI) <- "+init=epsg:4326"
centralLocation <- spTransform(cityOI, CRS = CRS(projection(cityMap)))
mile2meter <- function(x) { x * 1609.344 }
distLayer100<- rgeos::gBuffer(centralLocation, width = mile2meter(100))
distLayer50 <- rgeos::gBuffer(centralLocation, width = mile2meter(50))
distLayer25 <- rgeos::gBuffer(centralLocation, width = mile2meter(25))
plot(distLayer25, col = alpha("red", .0), add = TRUE)
plot(distLayer50, col = alpha("red", .0), add = TRUE)
plot(distLayer100, col = alpha("red", .0), add = TRUE)
# Tornado locations around city of interest
coordinates(Area_COI) <- ~ lon + lat
projection(Area_COI) <- "+init=epsg:4326"
tor_aroud_COI <- spTransform(Area_COI, CRS = CRS(projection(cityMap)))
points(tor_aroud_COI, cex = 1, pch = 20, col='blue')
# Add the Tornado related deaths around city of interest
# Generate a list of locations with DEATHS in the defined area.
DT_COI = filter(tor_DT, X %in% distance_matrix, DEATHS >0)
coordinates(DT_COI) <- ~ BEGIN_LON + BEGIN_LAT
projection(DT_COI) <- "+init=epsg:4326"
allIncidents2 <- spTransform(DT_COI, CRS = CRS(projection(cityMap))) # coordinate reference system (CRS)
points(allIncidents2, cex = 1, pch = 2, col='red')
###### COMPARISON BETWEEN TWO CITIES ############
locationCoords = tor_DT%>%dplyr::select(originalPlace=X, lon=BEGIN_LON, lat=BEGIN_LAT)
# Coordinates for the City of Interest (Change the city as much as you can!)
yourcity = "GandPraire, TX"
yourcity1 = "Dallas, TX"
# Enter the distance around the cities to search for Tornados
# This is the radius of a circle centered at the city
distance_from_city = 10
# Getting the geographic coordinates for each city
your_city = mutate(suppressMessages(geocode(yourcity)), originalPlace = (yourcity[1]))
your_city = your_city%>%dplyr::select(originalPlace, lon=longitude, lat=latitude)
your_city1 = mutate(suppressMessages(geocode(yourcity1)), originalPlace = (yourcity1[1]))
your_city1 = your_city1%>%dplyr::select(originalPlace, lon=longitude, lat=latitude)
# Getting the events in a radios from your_city
deg2rad <- function(deg) return(deg*pi/180)
gcd.slc <- function(long1, lat1, long2, lat2) {
long1 <- deg2rad(long1)
lat1 <- deg2rad(lat1)
long2 <- deg2rad(long2)
lat2 <- deg2rad(lat2)
R <- 6371 # Earth mean radius [km]
d <- acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2) * cos(long2-long1)) * R
d <- d*0.621371 #in miles
return(d) # Distance in miles
}
# Creating a matrix with the locations around the cities
dist <- gcd.slc(your_city$lon, your_city$lat, locationCoords$lon, locationCoords$lat)
dist_to_city <- which( dist <= distance_from_city)
events_near_your_city = rbind((filter(locationCoords, originalPlace %in% dist_to_city)),your_city)
events=tor_DT%>%filter(X %in% events_near_your_city$originalPlace)%>%dplyr::select(X,BEGIN_YEARMONTH, BEGIN_DAY, BEGIN_LAT, BEGIN_LON, DEATHS)
n_e = nrow(events)
dist1 <- gcd.slc(your_city1$lon, your_city1$lat, locationCoords$lon, locationCoords$lat)
dist_to_city1 <- which( dist1 <= distance_from_city )
events_near_your_city1 = rbind((filter(locationCoords, originalPlace %in% dist_to_city1)),your_city1)
events_1=tor_DT%>%filter(X %in% events_near_your_city1$originalPlace)%>%dplyr::select(X, BEGIN_YEARMONTH, BEGIN_DAY, BEGIN_LAT, BEGIN_LON, DEATHS)
n_e1= nrow(events_1)
common_events = merge(x=events, y=events_1)
com_ev=nrow(common_events)
# The result
cat("There were",n_e, "tornados", distance_from_city, "miles around", yourcity, "and", n_e1, "in", yourcity1,", Of these,",com_ev,"were common.")
# Create a column with the state abbreviation:
stateAbb <-function(x) {
# Modified from:
# https://favorableoutcomes.wordpress.com/2012/10/19/create-an-r-function-to-convert-state-codes-to-full-state-name/
# Read 52 state codes into local variable [includes DC (Washington D.C. and PR (Puerto Rico)]
# names need to be in lower case (use tolower() if necesary)
st.codes<-data.frame(
state=as.factor(c("alaska","alabama","arkansas","arizona","california","colorado",
"connecticut","district of columbia","delaware","florida","georgia",
"hawaii","iowa","idaho","illinois","indiana","kansas","kentucky",
"louisiana","massachusetts","maryland","maine","michigan","minnesota",
"missouri","mississippi","montana","north carolina","north dakota",
"nebraska","new hampshire","new jersey","new mexico","nevada",
"new york","ohio","oklahoma","oregon","pennsylvania","puerto rico",
"rhode island","south carolina","south dakota","tennessee","texas",
"utah","virginia","vermont","washington","wisconsin",
"west virginia","wyoming")),
abb=as.factor(c("AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
"HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME",
"MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM",
"NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN",
"TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY"))
)
# Create an nx1 data.frame of state codes from source column
st.x<-data.frame(state=x)
# Match source names with the abbreviations
refac.x<-st.codes$abb[match(st.x$state,st.codes$state)]
# Return the abbreviations
return(refac.x)
}
# Filter states and direct deaths only
s_state_2=s_state%>%filter(DEATH_TYPE=="DEATHS_DIRECT")
s_state_2=s_state_2%>%mutate(state=stateAbb(as.character(tolower(s_state_2$STATE))))%>%filter(state!="PR")%>%filter(state!="DC")
#Load geojson with US states boundaries
data("usgeojson")
#Map colors
n=4
# Option 1
colfunc <- colorRampPalette(c("white", "darkgreen"))
colstops <- data.frame(q = 0:n, c = colfunc(n+1)) %>%list_parse2()
# Option 2
colstops <- data.frame(q = 0:n/n, c = substring(viridis(n + 1, option = "D"), 0, 7)) %>% list_parse2()
#PLOT
highchart() %>%
hc_title(text = "Number of direct deaths by Tornados per US state") %>%
hc_subtitle(text = "Source: NOAA") %>%
hc_add_series_map(usgeojson, s_state_2, name = "No. Deaths", value = "sum", joinBy = c("postalcode", "state"),
dataLabels = list(enabled = TRUE, format = '{point.properties.postalcode}')) %>%
hc_colorAxis(stops = colstops) %>%
hc_mapNavigation(enabled = TRUE) -> deaths
deaths
# Save the widget as html
saveWidget(deaths, file="deaths.html")
cat("There were",n_e, "tornados", distance_from_city, "miles around", yourcity, "and", n_e1, "in", yourcity1,", Of these,",com_ev,"were common.")
year2="1965"
tor_scale_year = tornados_clean%>%filter(YEAR==year2)%>%group_by_(.dots=col_com)%>%dplyr::summarise(n=n())
ggplot(tor_scale_year,aes(x = TOR_F_SCALE,y = n)) +
geom_bar(stat="identity", aes(fill = TOR_F_SCALE),position = "dodge")+ guides(fill=FALSE) +
xlab("") + ylab("No. of Tornados")
tor_DT = tornados_clean %>% mutate(DEATHS = tornados_clean$DEATHS_DIRECT + tornados_clean$DEATHS_INDIRECT)
locationCoords = tor_DT%>%dplyr::select(originalPlace=X, lon=BEGIN_LON, lat=BEGIN_LAT)
locationCoords
locationCoords = tornados_clean%>%dplyr::select(originalPlace=X, lon=BEGIN_LON, lat=BEGIN_LAT)
yourcity = "GandPraire, TX"
yourcity1 = "Dallas, TX"
# Enter the distance around the cities to search for Tornados
# This is the radius of a circle centered at the city
distance_from_city = 10
# Getting the geographic coordinates for each city
your_city = mutate(suppressMessages(geocode(yourcity)), originalPlace = (yourcity[1]))
your_city = your_city%>%dplyr::select(originalPlace, lon=longitude, lat=latitude)
your_city1 = mutate(suppressMessages(geocode(yourcity1)), originalPlace = (yourcity1[1]))
your_city1 = your_city1%>%dplyr::select(originalPlace, lon=longitude, lat=latitude)
# Getting the events in a radios from your_city
deg2rad <- function(deg) return(deg*pi/180)
gcd.slc <- function(long1, lat1, long2, lat2) {
long1 <- deg2rad(long1)
lat1 <- deg2rad(lat1)
long2 <- deg2rad(long2)
lat2 <- deg2rad(lat2)
R <- 6371 # Earth mean radius [km]
d <- acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2) * cos(long2-long1)) * R
d <- d*0.621371 #in miles
return(d) # Distance in miles
}
# Creating a matrix with the locations around the cities
dist <- gcd.slc(your_city$lon, your_city$lat, locationCoords$lon, locationCoords$lat)
dist_to_city <- which( dist <= distance_from_city)
events_near_your_city = rbind((filter(locationCoords, originalPlace %in% dist_to_city)),your_city)
events=tor_DT%>%filter(X %in% events_near_your_city$originalPlace)%>%dplyr::select(X,BEGIN_YEARMONTH, BEGIN_DAY, BEGIN_LAT, BEGIN_LON, DEATHS)
n_e = nrow(events)
dist1 <- gcd.slc(your_city1$lon, your_city1$lat, locationCoords$lon, locationCoords$lat)
dist_to_city1 <- which( dist1 <= distance_from_city )
events_near_your_city1 = rbind((filter(locationCoords, originalPlace %in% dist_to_city1)),your_city1)
events_1=tor_DT%>%filter(X %in% events_near_your_city1$originalPlace)%>%dplyr::select(X, BEGIN_YEARMONTH, BEGIN_DAY, BEGIN_LAT, BEGIN_LON, DEATHS)
n_e1= nrow(events_1)
common_events = merge(x=events, y=events_1)
com_ev=nrow(common_events)
# The result
cat("There were",n_e, "tornados", distance_from_city, "miles around", yourcity, "and", n_e1, "in", yourcity1,", Of these,",com_ev,"were common.")
tor_one_year
shiny::runApp('~/Google Drive/Tornado_US_Coursera/Tornado_US')