-
Notifications
You must be signed in to change notification settings - Fork 0
/
rdb_build.rmd
1057 lines (670 loc) · 25.8 KB
/
rdb_build.rmd
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Design and build a RDb"
author: "Jai Iyyappa Vignesh Manivannan"
output:
html_document:
df_print: paged
---
####Implementing my ER diagram into relational table using MySQL.
```{r}
# Installing the RMySQL Library
library(RMySQL)
# MySQL Settings
db_user <- 'admin'
db_password <- 'dbpass'
db_name <- 'dbname'
db_host <- 'hostname'
db_port <- 3306
# Establishing a connection to MySQL
mydb <- dbConnect(MySQL(), user = db_user, password = db_password,
dbname = db_name, host = db_host, port = db_port)
```
### Load CSV Data
```{r loadCSV}
fn <- "BirdStrikesData.csv"
df.raw <- read.csv(file = fn,
header = T,
stringsAsFactors = F)
```
```{r displayLoadedcsv}
head(df.raw, 3)
```
### Omitting empty aircraft data
#### All entries which didn't have aircraft info didn't have the airport information, so omitting it.
```{r removeEmptyAircraftDataFromexcel}
totalRowBeforeOmit <- nrow(df.raw)
df.newRaw <- df.raw
if(any(df.raw$ Airport..Name == "")) {
rs = which(df.raw$ Airport..Name == "")
df.newRaw <- df.raw[-rs,]
}
totalNewRowAfterOmit <- nrow(df.newRaw)
```
```{r message=FALSE}
detach("package:RMySQL")
library(sqldf)
```
### Table creation based on the ER diagram
* The data is divided to 8 lookup table and 3 information table which is stored based on recordId
### Dropping reference table Accidents
```{sql connection=mydb}
DROP TABLE IF EXISTS Accidents
```
### Creation of table Airport
* airportId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS Airport
```
```{sql connection=mydb}
CREATE TABLE Airport(
airportId INT NOT NULL,
airportName VARCHAR(255) NOT NULL,
PRIMARY KEY (airportId)
)
```
### Extract the Airport Data from excel
```{r extractAirportData}
# Extracting the airport data from excel into a dataframe df.Airport.
df.Airport <- sqldf::sqldf("select 1 as airportId, `Airport..Name` as airportName from `df.newRaw` group by airportName")
# Calculating the total number of rows in df.Airport created.
n.Airport <- nrow(df.Airport)
# Changing the sequence number of hard-coded airportId value for PK.
df.Airport[,1] <- seq(1, n.Airport)
```
### Inserting the airport data into table
```{r insertAirportDataIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'Airport', df.Airport, row.names=F,append=T, overwrite=F)
```
### Display Airport table
```{sql connection=mydb}
SELECT * FROM Airport
LIMIT 5;
```
### Creation of table Airline
* airlineId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS Airline
```
```{sql connection=mydb}
CREATE TABLE Airline(
airlineId INT NOT NULL,
airlineOperator VARCHAR(255) NOT NULL,
PRIMARY KEY (airlineId)
)
```
### Extract the Airline Data from excel
```{r extractAirlineData}
# Extracting the Airline data from excel into a dataframe df.Airline
df.Airline <- data.frame(
airlineId = 1,
airlineOperator = unique(df.newRaw$Aircraft..Airline.Operator)
)
# Calculating the total number of rows in df.Airline created.
n.Airline <- nrow(df.Airline)
# Changing the sequence number of hard-coded airlineId value for PK.
df.Airline[,1] <- seq(1, n.Airline)
```
### Inserting the Airline data into table
```{r insertAirlineDataIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'Airline', df.Airline, row.names=F, append=T, overwrite=F)
```
### Display Airline table
```{sql connection=mydb}
SELECT * FROM Airline
LIMIT 5;
```
### Creation of table Aircraft
* aircraftId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS Aircraft
```
```{sql connection=mydb}
CREATE TABLE Aircraft(
aircraftId INT NOT NULL,
aircraftMake VARCHAR(100) NOT NULL,
PRIMARY KEY (aircraftId)
)
```
### Extract the Aircraft Data from excel
```{r extractAircraftData}
# Extracting the Aircraft data from excel into a dataframe df.Aircraft
df.Aircraft <- data.frame(
aircraftId = 1,
aircraftMake = unique(df.newRaw$Aircraft..Make.Model)
)
# Calculating the total number of rows in df.Aircraft created.
n.Aircraft <- nrow(df.Aircraft)
# Changing the sequence number of hard-coded aircraftId value for PK.
df.Aircraft[,1] <- seq(1, n.Aircraft)
```
### Inserting the Aircraft data into table
```{r insertAircraftDataIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'Aircraft', df.Aircraft, row.names=F, append=T, overwrite=F)
```
### Display Aircraft table
```{sql connection=mydb}
SELECT * FROM Aircraft
LIMIT 5;
```
### Creation of table PhaseOfFlight
* phaseId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS PhaseOfFlight
```
```{sql connection=mydb}
CREATE TABLE PhaseOfFlight(
phaseId INT NOT NULL,
phaseName VARCHAR(100) NOT NULL,
PRIMARY KEY (phaseId)
)
```
### Extract the PhaseOfFlight Data from excel
```{r extractPhaseOfFlightData}
# Extracting the PhaseOfFlight data from excel into a dataframe df.PhaseOfFlight with hardcoded phaseId
df.PhaseOfFlight <- data.frame(
phaseId = 1,
phaseName = unique(df.newRaw$When..Phase.of.flight)
)
# Calculating the total number of rows in df.PhaseOfFlight created.
n.PhaseOfFlight <- nrow(df.PhaseOfFlight)
# Changing the sequence number of hard-coded phaseId value for PK.
df.PhaseOfFlight[,1] <- seq(1, n.PhaseOfFlight)
```
### Inserting the PhaseOfFlight data into table
```{r insertPhaseOfFlightDataIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'PhaseOfFlight', df.PhaseOfFlight, row.names=F, append=T, overwrite=F)
```
#### Display PhaseOfFlight table
```{sql connection=mydb}
SELECT * FROM PhaseOfFlight
LIMIT 5;
```
### Creation of table Wildlife
* wildlifeId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS Wildlife
```
```{sql connection=mydb}
CREATE TABLE Wildlife(
wildlifeId INT NOT NULL,
wildlifeName VARCHAR(100) NOT NULL,
PRIMARY KEY (wildlifeId)
)
```
### Extract the Wildlife Data from excel
```{r extractWildlifeData}
# Extracting the Wildlife data from excel into a dataframe df.Wildlife with hardcoded wildlifeId
df.Wildlife <- data.frame(
wildlifeId = 1,
wildlifeName = unique(df.newRaw$Wildlife..Species)
)
# Calculating the total number of rows in df.Wildlife created.
n.Wildlife <- nrow(df.Wildlife)
# Changing the sequence number of hard-coded wildlifeId value for PK.
df.Wildlife[,1] <- seq(1, n.Wildlife)
```
### Inserting the Wildlife data into table
```{r insertWildlifeIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'Wildlife', df.Wildlife, row.names=F, append=T, overwrite=F)
```
### Display Wildlife table
```{sql connection=mydb}
SELECT * FROM Wildlife
LIMIT 5;
```
### Creation of table precipitateCondition
* pConditionId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS accidentPrecipitateMap
```
```{sql connection=mydb}
DROP TABLE IF EXISTS precipitateCondition
```
```{sql connection=mydb}
CREATE TABLE precipitateCondition(
pConditionId INT NOT NULL,
pConditionName VARCHAR(100) NOT NULL,
PRIMARY KEY (pConditionId)
)
```
### Extract the precipitateCondition Data from excel
```{r extractprecipitateConditionData}
s <- strsplit(unique(df.newRaw$Conditions..Precipitation) , ",")
s <- unlist(s)
s <- gsub( " ", "", s)
# Extracting the precipitateCondition data from excel into a dataframe df.precipitateCondition with hardcoded pConditionId
df.precipitateCondition <- data.frame(
pConditionId = 1,
pConditionName = unique(s)
)
# Calculating the total number of rows in df.precipitateCondition created.
n.precipitateCondition <- nrow(df.precipitateCondition)
# Changing the sequence number of hard-coded pConditionId value for PK.
df.precipitateCondition[,1] <- seq(1, n.precipitateCondition)
```
### Inserting the precipitateCondition data into table
```{r insertprecipitateConditionIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'precipitateCondition', df.precipitateCondition, row.names=F, append=T, overwrite=F)
```
### Display precipitateCondition table
```{sql connection=mydb}
SELECT * FROM precipitateCondition
LIMIT 5;
```
### Creation of table accidentPrecipitateMap
* recordPrecipMapId is the PRIMARY KEY
* pConditionId is the FOREIGN KEY references the value in precipitateCondition table
```{sql connection=mydb}
DROP TABLE IF EXISTS accidentPrecipitateMap
```
```{sql connection=mydb}
CREATE TABLE accidentPrecipitateMap(
recordPrecipMapId INT NOT NULL,
recordId INT NOT NULL,
pConditionId INT NOT NULL,
PRIMARY KEY (recordPrecipMapId),
FOREIGN KEY (pConditionId) REFERENCES precipitateCondition(pConditionId)
)
```
```{r extractaccidentPrecipitateMapData}
# separating the multi valued column values into singular value.
totalPreciData <- strsplit(df.newRaw$Conditions..Precipitation , ",")
# Creating a data frame with unique pricipitation value - removing redundant data.
# gsub removes space.
# Extracting the accidentPrecipitateMap data from excel into a dataframe df.accidentPrecipitateMap with hardcoded recordPrecipMapId
df.accidentPrecipitateMap <- data.frame(
recordPrecipMapId = 1,
recordId = rep(df.newRaw$ï..Record.ID, sapply(totalPreciData,length)),
pConditionId = gsub( " ", "",unlist(totalPreciData))
)
# Calculating the total number of rows in df.accidentPrecipitateMap created.
n.accidentPrecipitateMap <- nrow(df.accidentPrecipitateMap)
# Changing the sequence number of hard-coded recordPrecipMapId value for PK.
df.accidentPrecipitateMap[,1] <- seq(1, n.accidentPrecipitateMap)
tempaAccidentPrecipitateMapRs <- df.accidentPrecipitateMap
# Linking the references from the lookup table with corresponding Id.
for (r in 1:nrow(tempaAccidentPrecipitateMapRs)){
precipCond <- df.precipitateCondition$pConditionId[which(df.precipitateCondition$pConditionName == tempaAccidentPrecipitateMapRs$pConditionId[r])]
tempaAccidentPrecipitateMapRs$pConditionId[r] <- precipCond
}
tempaAccidentPrecipitateMapRs$pConditionId <- as.integer(as.character(tempaAccidentPrecipitateMapRs$pConditionId))
df.accidentPrecipitateMap <- tempaAccidentPrecipitateMapRs
```
### Inserting the accidentPrecipitateMap data into table
```{r insertaccidentPrecipitateMapIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'accidentPrecipitateMap', df.accidentPrecipitateMap, row.names=F, append=T, overwrite=F)
```
### Display accidentPrecipitateMap table
```{sql connection=mydb}
SELECT * FROM accidentPrecipitateMap
LIMIT 5;
```
### Drop of table accidentCondition
```{sql connection=mydb}
DROP TABLE IF EXISTS accidentCondition
```
### Creation of table originState
* stateId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS originState
```
```{sql connection=mydb}
CREATE TABLE originState(
stateId INT NOT NULL,
stateName VARCHAR(100) NOT NULL,
PRIMARY KEY (stateId)
)
```
### Extract the originState Data from excel
```{r extractoriginStateData}
# Extracting the originState data from excel into a dataframe df.originState with hardcoded stateId
df.originState <- data.frame(
stateId = 1,
stateName = unique(df.newRaw$Origin.State)
)
# Calculating the total number of rows in df.originState created.
n.originState <- nrow(df.originState)
# Changing the sequence number of hard-coded stateId value for PK.
df.originState[,1] <- seq(1, n.originState)
```
### Inserting the originState data into table
```{r insertoriginStateIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'originState', df.originState, row.names=F, append=T, overwrite=F)
```
### Display originState table
```{sql connection=mydb}
SELECT * FROM originState
LIMIT 5;
```
### Creation of table skyCondition
* sConditionId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS skyCondition
```
```{sql connection=mydb}
CREATE TABLE skyCondition(
sConditionId INT NOT NULL,
sConditionName VARCHAR(100) NOT NULL,
PRIMARY KEY (sConditionId)
)
```
### Extract the skyCondition Data from excel
```{r extractskyConditionData}
# Extracting the skyCondition data from excel into a dataframe df.skyCondition with hardcoded sConditionId
df.skyCondition <- data.frame(
sConditionId = 1,
sConditionName = unique(df.newRaw$Conditions..Sky)
)
# Calculating the total number of rows in df.skyCondition created.
n.skyCondition <- nrow(df.skyCondition)
# Changing the sequence number of hard-coded sConditionId value for PK.
df.skyCondition[,1] <- seq(1, n.skyCondition)
```
### Inserting the skyCondition data into table
```{r insertskyConditionIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, 'skyCondition', df.skyCondition, row.names=F, append=T, overwrite=F)
```
### Display skyCondition table
```{sql connection=mydb}
SELECT * FROM skyCondition
LIMIT 5;
```
### Creation of table accidentCondition
* recordId is the PRIMARY KEY
* stateId is the FOREIGN KEY references the stateId from originState table
* sConditionId is the FOREIGN KEY references the sConditionId from skyCondition table
```{sql connection=mydb}
DROP TABLE IF EXISTS accidentCondition
```
```{sql connection=mydb}
CREATE TABLE accidentCondition(
recordId INT NOT NULL,
sConditionId INT NOT NULL,
pConditionName VARCHAR(100),
stateId INT NOT NULL,
PRIMARY KEY (recordId),
FOREIGN KEY (stateId) REFERENCES originState(stateId),
FOREIGN KEY (sConditionId) REFERENCES skyCondition(sConditionId)
)
```
### table accidentCondition extract data from excel
```{r accidentCondition}
# Extracting the accidentCondition data from excel into a dataframe df.accidentCondition with hardcoded recordId
df.accidentCondition <- data.frame(
recordId = df.newRaw$ï..Record.ID,
sConditionId = df.newRaw$Conditions..Sky,
pConditionName = df.newRaw$Conditions..Precipitation,
stateId = df.newRaw$Origin.State
)
tempaccidentConditionRs <- df.accidentCondition
# linking the foreign key value from reference dataframes df.skyCondition and df.originState whcih are used to build table.
for (r in 1:nrow(tempaccidentConditionRs)){
skyCondition <- df.skyCondition$sConditionId[which(df.skyCondition$sConditionName == tempaccidentConditionRs$sConditionId[r])]
tempaccidentConditionRs$sConditionId[r] <- skyCondition
state <- df.originState$stateId[which(df.originState$stateName == tempaccidentConditionRs$stateId[r])]
tempaccidentConditionRs$stateId[r] <- state
}
tempaccidentConditionRs$sConditionId <- as.integer(as.character(tempaccidentConditionRs$sConditionId))
tempaccidentConditionRs$stateId <- as.integer(as.character(tempaccidentConditionRs$stateId))
df.accidentCondition <- tempaccidentConditionRs
```
### Insert accidentCondition Data into table
```{r accidentConditionToTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, "accidentCondition", df.accidentCondition, row.names=F, append=T, overwrite=F)
```
### Display Accidents table
```{sql connection=mydb}
SELECT * FROM accidentCondition
LIMIT 5;
```
### Creation of table damageData
* recordId is the PRIMARY KEY
```{sql connection=mydb}
DROP TABLE IF EXISTS damageData
```
```{sql connection=mydb}
CREATE TABLE damageData(
recordId INT NOT NULL,
impactToFlight VARCHAR(255),
IndicatedDamage VARCHAR(255),
wildlifeRemainsCollected BOOLEAN,
wildlifeRemainsSmithsonian BOOLEAN,
numberOfPeopleInjured INT,
cost INT,
remarks VARCHAR(1000) default 'NA',
PRIMARY KEY (recordId)
)
```
### Extract the damage Data from excel
```{r DamageData}
# Extracting the damage data from excel into a dataframe df.damageData
df.damageData <- data.frame(
recordId = df.newRaw$ï..Record.ID,
impactToFlight = df.newRaw$Effect..Impact.to.flight,
IndicatedDamage = df.newRaw$Effect..Indicated.Damage,
wildlifeRemainsCollected = df.newRaw$Remains.of.wildlife.collected.,
wildlifeRemainsSmithsonian = df.newRaw$Remains.of.wildlife.sent.to.Smithsonian,
numberOfPeopleInjured = df.newRaw$Number.of.people.injured,
cost = df.newRaw$Cost..Total..,
remarks = gsub("'", "''", df.newRaw$Remarks)
)
n.damageData <- nrow(df.damageData)
```
### Inserting the damageData data into table
```{r insertdamageDataIntoTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, "damageData", df.damageData, row.names=F, append=T, overwrite=F)
```
### Display damageData table
```{sql connection=mydb}
SELECT * FROM damageData
LIMIT 5;
```
### Creation of table Accidents
* recordId is the PRIMARY KEY
* airportId is the FOREIGN KEY references the airportId from Airport table
* airlineId is the FOREIGN KEY references the airlineId from Airline table
* aircraftId is the FOREIGN KEY references the aircraftId from Aircraft table
* phaseOfFlight is the FOREIGN KEY references the phaseOfFlight from PhaseOfFlight table
* wildlifeSpecies is the FOREIGN KEY references the wildlifeSpecies from Wildlife table
```{sql connection=mydb}
DROP TABLE IF EXISTS Accidents
```
```{sql connection=mydb}
CREATE TABLE Accidents(
recordId INT NOT NULL,
airportId INT NOT NULL,
airlineId INT NOT NULL,
aircraftId INT NOT NULL,
flightDate DATE,
feetAboveGround INT,
WildlifeNumberStruckActual INT,
phaseOfFlight INT,
wildlifeSpecies INT,
PRIMARY KEY (recordId),
FOREIGN KEY (airportId) REFERENCES Airport(airportId),
FOREIGN KEY (airlineId) REFERENCES Airline(airlineId),
FOREIGN KEY (aircraftId) REFERENCES Aircraft(aircraftId),
FOREIGN KEY (phaseOfFlight) REFERENCES PhaseOfFlight(phaseId),
FOREIGN KEY (wildlifeSpecies) REFERENCES Wildlife(wildlifeId)
)
```
### Accidents Data
```{r AccidentsData}
# Extracting the Accidents data from excel into a dataframe df.Accidents
df.Accidents <- data.frame(
recordId = df.newRaw$ï..Record.ID,
airportId = df.newRaw$Airport..Name,
airlineId = df.newRaw$Aircraft..Airline.Operator,
aircraftId = df.newRaw$Aircraft..Make.Model,
flightDate = df.newRaw$FlightDate,
feetAboveGround = df.newRaw$Feet.above.ground,
WildlifeNumberStruckActual = df.newRaw$Wildlife..Number.Struck.Actual,
phaseOfFlight = df.newRaw$When..Phase.of.flight,
wildlifeSpecies = df.newRaw$Wildlife..Species
)
tempAccidentRs <- df.Accidents
# linking the foreign key value from reference table
for (r in 1:nrow(tempAccidentRs)){
airport <- df.Airport$airportId[which(df.Airport$airportName == tempAccidentRs$airportId[r])]
tempAccidentRs$airportId[r] <- airport
airline <- df.Airline$airlineId[which(df.Airline$airlineOperator == tempAccidentRs$airlineId[r])]
tempAccidentRs$airlineId[r] <- airline
aircraft <- df.Aircraft$aircraftId[which(df.Aircraft$aircraftMake == tempAccidentRs$aircraftId[r])]
tempAccidentRs$aircraftId[r] <- aircraft
flightPhase <- df.PhaseOfFlight$phaseId[which(df.PhaseOfFlight$phaseName == tempAccidentRs$phaseOfFlight[r])]
tempAccidentRs$phaseOfFlight[r] <- flightPhase
wildLifeName <- df.Wildlife$wildlifeId[which(df.Wildlife$wildlifeName == tempAccidentRs$wildlifeSpecies[r])]
tempAccidentRs$wildlifeSpecies[r] <- wildLifeName
}
#Casting all characters to integer type
tempAccidentRs$airportId <- as.integer(as.character(tempAccidentRs$airportId))
tempAccidentRs$airlineId <- as.integer(as.character(tempAccidentRs$airlineId))
tempAccidentRs$aircraftId <- as.integer(as.character(tempAccidentRs$aircraftId))
tempAccidentRs$phaseOfFlight <- as.integer(as.character(tempAccidentRs$phaseOfFlight))
tempAccidentRs$wildlifeSpecies <- as.integer(as.character(tempAccidentRs$wildlifeSpecies))
# Converting the date format present
tempAccidentRs$flightDate <- as.Date(tempAccidentRs$flightDate, tryFormats = c("%m-%d-%Y", "%m/%d/%Y"),
optional = FALSE)
df.Accidents <- tempAccidentRs
```
### Insert Accidents Data into table
```{r AccidentsDataToTable}
# dbWriteTable is used with append to insert the data from dataframe into table.
dbWriteTable(mydb, "Accidents", df.Accidents, row.names=F, append=T, overwrite=F)
```
### Display Accidents table
```{sql connection=mydb}
SELECT * FROM Accidents
LIMIT 5;
```
## Question 4
```{sql connection=mydb}
SELECT al.airlineOperator, COUNT(recordId) AS 'No of incidents' FROM Accidents acc
LEFT JOIN Airline al USING (airlineId)
WHERE acc.phaseOfFlight = 1 OR
acc.phaseOfFlight = 4
GROUP BY al.airlineOperator;
```
## Question 5
```{sql connection=mydb}
SELECT ap.airportName, COUNT(recordId) AS 'No of incidents' FROM Accidents acc
LEFT JOIN Airport ap USING (airportId)
GROUP BY ap.airportName
ORDER BY `No of incidents` DESC;
```
## Question 6
```{sql connection=mydb}
SELECT YEAR(acc.flightDate) AS 'Year', COUNT(recordId) AS 'No of incidents' FROM Accidents acc
GROUP BY YEAR(acc.flightDate)
ORDER BY YEAR(acc.flightDate);
```
## Question 7
```{r}
# construct a SQL query
sqlCmdData1 = "SELECT YEAR(acc.flightDate) AS 'Year', COUNT(recordId) AS 'No of incidents' FROM Accidents acc
WHERE acc.phaseOfFlight = 1 OR
acc.phaseOfFlight = 4
GROUP BY YEAR(acc.flightDate)
HAVING `Year` >= 2008 AND
`Year` <= 2011
ORDER BY `Year`"
# send the SQL query to the database
tempQ7Data1 = dbGetQuery(mydb, sqlCmdData1)
# construct a SQL query
sqlCmdData2 = "SELECT YEAR(acc.flightDate) AS 'Year', COUNT(recordId) AS 'No of incidents' FROM Accidents acc
WHERE acc.phaseOfFlight = 2 OR
acc.phaseOfFlight = 3 OR
acc.phaseOfFlight = 5
GROUP BY YEAR(acc.flightDate)
HAVING `Year` >= 2008 AND
`Year` <= 2011
ORDER BY `Year`"
# send the SQL query to the database
tempQ7Data2 = dbGetQuery(mydb, sqlCmdData2)
```
### Graph Plot with year as X axis and number of incidents as Y
```{r}
# Graph Plot with year as X axis and number of incidents as Y
tempRs <- sqldf("select Year , al.'No of incidents' AS `I1`, ap.'No of incidents' AS `I2` from tempQ7Data1 al
LEFT JOIN tempQ7Data2 ap USING (Year)")
#Taking the Dataset mentioned in the question
df = data.frame(Block = tempRs$Year, RTreg = tempRs$I1, RTrnd = tempRs$I2)
#Create a Matrix which will help in creating the plot
value_matrix = matrix( nrow = 2, ncol = 4)
value_matrix[1,] = df$RTreg
value_matrix[2,] = df$RTrnd
#Note that the "beside" argument has to be kept "TRUE" in order to place the bars side by side
yearBar <- barplot(value_matrix, names.arg = df$Block, beside = TRUE, col = c("peachpuff", "skyblue"),
main="Bird strike incidents in different phase of flight from 2008 to 2011", ylab="Number of Incidents",
xlab = "Year", ylim = c(0, 3500), args.legend = list(title = "Phase of flight", x = "topright"),
legend.text = c("Take-off/climbing","Descent/approach/landing"))
text(yearBar, value_matrix , labels = value_matrix, xpd = T, srt=90, adj = c(2,0))
```
### Graph Plot with phase of flight as X axis and number of incidents as Y
```{r}
## Graph Plot with phase of flight as X axis and number of incidents as Y
col1 <- tempQ7Data1$`No of incidents`
col2 <- tempQ7Data2$`No of incidents`
legendcol <- tempQ7Data2$Year
data <- data.frame(col1,col2)
names(data) <- c("Take-off/climbing","Descent/approach/landing")
bar <- barplot(height=as.matrix(data), main="Incidents during different phase of flight from 2008 to 2011", ylab="Number of Incidents", xlab = "Phase of flight" ,legend.text = legendcol, beside=TRUE,col=rainbow(4), ylim = c(0, 2500),
args.legend = list(title = "Year", x = "topleft", inset = c(0.10, 0)))
text(bar, as.matrix(data) , labels = as.matrix(data), xpd = T, srt=90, adj = c(2,0))
```
## Question 7
### Initial check based on condition and getting count
```{sql connection=mydb}
SELECT COUNT(*)
FROM Accidents
WHERE airlineId = (
SELECT airlineId
FROM Airline WHERE airlineOperator = 'AIR CANADA'
);