-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvi_Recovered.Rmd
More file actions
2036 lines (1277 loc) · 58.6 KB
/
vi_Recovered.Rmd
File metadata and controls
2036 lines (1277 loc) · 58.6 KB
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: "NYC311 Dataset Analytics"
author: 'David_Mwasikira'
date: "2/14/2020"
output:
pdf_document: default
html_document:
df_print: paged
always_allow_html: yes
---
```{r setup, include=FALSE}
#Global settings
knitr::opts_chunk$set(
echo = FALSE,
eval = TRUE,
message=FALSE,
warning=FALSE,
error = TRUE,
collapse= TRUE)
library(knitr)
library(kableExtra)
```
## Project Title: NYC311 Preliminary Data Exploration & Analysis
* Course Title: Master of Science - Data Analytics
* RIT Dubai University
* Professor: Mike McQuaid
```{r echo=FALSE}
# This chunk is just to make it possible to shrink the typeface in succeeding chunks.
# Mainly this will be used for the crosstabs.
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
ifelse(options$size != "normalsize", paste0("\\", options$size,"\n\n", x, "\n\n \\normalsize"), x)
})
```
## 1. Introduction
The NYC311 is the nation’s largest and most comprehensive 311 service in operation that deals with non-emergency cases within the jurisdiction of New York City. The data collected through this service is available as is to the public for viewing and analysis.
The NYC311 data being in its raw state poses several challenges for any immediate analysis and therefore requires some treatment or conditioning to make it more friendlier for analytical tools. We therefore pass this data through a series of steps in what is known as data wrangling before we start extracting some insights from it.
Data wrangling refers to the process of cleaning, restructuring and enriching the raw data available into a more usable format. Organizing and cleaning data before analysis has been shown to be extremely useful and helps in sppeding up the analysis of larger amounts of data.
We will approach the data with the following steps:
*1. Discovering:* Performing preliminary checks using str, colnames, nrow commands
*2. Structuring:* Restructuring data in a way that suits the analytical methods like splitting columns, dropping unwanted columns, etc
*3. Cleaning:* All datasets are sure to have some outliers, which can skew the results of the analysis. Null values will have to be changed, and the formatting will be standardized in order to make the data of higher quality.
*4. Enriching:* Augmenting the dataset using some additional data in order to make it better.
*5. Validating:* Validation rules refer to some repetitive programming steps which are used to verify the consistency and quality of the data you have to ascertain whether the fields in the data set are accurate via a check across the data
*6. Data Analysis:* Preparing Plots, Charts, tables and other analysis to discover trends or insights in the data
*7. Reporting:* The story telling part in a way that is truthful, impactful and beneficial.
## 2. Context
New York City, the most populous metropolitan area in the United States, is home to over 8.3 million residents. To serve this massive and diverse population the City operates the nation’s largest and most complex municipal government with more than 350,000 city employees and 120 agencies, offices and organizations offering over 4,000 different services to residents.
**What NYC311 Service Delivers**
The NYC311 is a call center service in New York city that provides you access to non-emergency City services and information about City government programs. NYC311 can help with a broad range of services, including things like homeless person assistance, pothole repair, or help understanding a property tax bill.
Residents of NewYork use the NYC311 App to log in complaints in a central database with enough details of location and nature of problem which are then picked up at the call centre and routed to relevant resolving departments. Once issue has been resolved, it is then logged as resolved and closed in the system.
A quick representation of information flow would look as depicted below:

Complaints received from residents through the NYC311 App service, online, text and other means are assigned to speciality departments for resolution.
First of all we will give a preliminary description of the dataset by reading the data then describe it in a way to define the dataset structure, data dictionary including all described pictures and tables required.
Further in this project we will deep dive into the data in order to explore insights and answer the business questions through the data analytics process.
We will attempt to answer questions on the data that are designed to open up insights, which can possibly lead to further information discovery. Links and correlations on data features shall be explored as given here:
- Connection between columns ( Correlation; what, which, when, where )
- Raise business Questions & Answers
**Questions We Raise**
1. What are the Statistics in regard to NYC311 dataset?
a. Aggregate Complaints Calls by Dates (including year, month and day), Agency, County
b. What types of complaints are dominant and how do they vary from region to region?
c. What is the total number of calls a department handles per month?
d. Which region generates the highest number of calls and of which type?
d. What is the association between Complaints and Boroughs?
2. What is the seasonality, trends of the complaints over time, and which type of complaint?
3. How do the agencies fare in dealing with complaints? Are there signs of being overwhelmed? If yes at what times?
a. What is the average time it takes to handle each category of task?
5. How could these data be made useful and benefit the agencies in improving their performance?
## 3. About The Data
### 3.1 The NewYork City 311 (NYC311) Dataset
**NYC311 Dataset Overview**
*Data Description*
The dataset was downloaded from a source provided
by [Khalil Darwish](https://drive.google.com/drive/folders/1c8JvmiUdn7B_ftqk8eQ0R5bRRfqrqaJW?usp=sharing)
The following steps are used in the process of data discovery and data cleaning for the new dataset as well.
i. Loading New Dataset
ii. Loading New Dataset
iii.Data Discovery - checking summaries and counts
iv. Removing duplicates
v. Data Cleaning
**Setting up The Workspace Environment**
- We are using the R language and RStudio Cloud the IDE for all our analysis. Link is https://rstudio.cloud/project/917416
- However there is a 3 GB limitation on storage space, so we trimmed our dataset to a smaller set of 100,000 rows each.
- We thereafter run the complete dataset on our laptops.
*Loading Required Packages*
The following packages are used in this project:
- Tidyverse: This is a package of packages which include ggplot2, dplyr, tidyr, readr, stringr, tibble, forcats, purrr, lubridate, magrittr among others. The purpose of tidyverse is to provide key data transformation functions in a single package, and moreover the packages work in harmony to clean, process, model, and visualize data.
- Data.Table: It is widely used for fast aggregation of large datasets, low latency add/update/remove of columns, quicker ordered joins, and a fast file reader. It is an ideal package for dataset handing in R.
- DT Package: For rendering Tables
- Hmisc: Hmisc is a multiple purpose package useful for data analysis, high – level graphics, imputing missing values, advanced table making, model fitting & diagnostics (linear regression, logistic regression & cox regression) etc.
- xtable:
- Leaflet: For rendering maps
- Corrplot Package: For Cross Tabulation
- Lubridate: For converting Dates from other formats to POSIXct and POSIXlt formats
```{r initialize, message=FALSE}
# Load the packages into R
library(plyr)
library(tidyverse, warn.conflicts = FALSE)
library(data.table, warn.conflicts = FALSE)
library(DT)
library(Hmisc)
library(xtable)
library(leaflet)
library(corrplot)
library(ggmap)
#library(rworldmap)
```
*Loading The NYC311 Dataset*
```{r raw_data1, message=FALSE}
if (!require(data.table)) {
install.packages("data.table",dependencies=TRUE)
library(data.table)
}
nyc311<-fread("311_Service_Requests_from_2010_to_Present.csv")
#nyc311<-fread("nyc311_sample.csv")
names(nyc311)<-names(nyc311) %>%
stringr::str_replace_all("\\s", ".")
```
The NYC311 2010 to 2014 dataset originally has:
- Number of Rows
```{r}
nrow(nyc311)
```
- Number of Columns
```{r}
ncol(nyc311)
```
```{r chart-colors, echo=FALSE}
#Creating Color Variables for use in Plot Fills
fillColor1 = "#0080FF"
fillColor2 = "#00FFFF"
fillColor3 = "#81C0FF"
fillColor4 = "#00FF00"
fillColor5 = "#FF00FF"
```
**Step 1: Data Discovery Preliminary Data Inspection**
*Dataset Features: The 52 Columns of the NYC311 Data*
```{r column_in_data1}
colnames(nyc311)
```
```{r view-1, eval=FALSE}
#A Table of Preview of The Original NYC311 Dataset
library(devtools)
library(pander)
#pander(head(cleaned_nyc311))
landscape(knitr::kable(nyc311[1:6, 1:52], caption = "Original NYC311 Data Display") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
```
A preliminary look into the data shows we have 9.4 millions rows and 52 columns. The first characteristics we note with our dataset are listed as follows;
- The NYC311 dataset is a dataframe.
- We also have empty columns in our dataset.
- All columns data are in char format except latitude and longitude
**Step 2-4: Data Structuring, Cleaning and Enriching to Improve Dataset**
```{r sample1, message=FALSE,warning=FALSE}
#Creating a Sample SubDataset for testing with 10,000 rows (records)
nyc311_sample<-nyc311[sample(nrow(nyc311),10000),]
```
The NYC311 Dataset is over 9 Million in rows and over 4 GB in size. To be able to easily explore the data, we create a small sample of a 10,000 rows of the original where we can do the testing.
We are now set to use the Data Wrangling steps in preparing the data for analysis. The steps here are iterative in nature and sometimes are performed together for clarity.
**Step 1. Data Discovery: Initial Checks for data structure, Duplicates**
Checked for how many unique values there are for each column
```{r message=FALSE,warning=FALSE, eval=FALSE, results="hide"}
kable(sapply(nyc311,function(x) length(unique(x))))
```
**Step 2. Structuring The Data: Dropping of unnecessary columns, Renaming Columns**
*Removing Columns with no data using various methods as outlined below:*
- select and contain "School" and "Facility" keywords
- use of rm keyword to remove "City, Landmark and Location" columns
- use of contain statement
```{r data_cleaning1, message=FALSE,warning=FALSE}
my_data<- nyc311
data1 <-within(my_data, rm(City,
Landmark,
Location,
Agency.Name,
Community.Board,
Park.Borough,
Street.Name,
Cross.Street.1,
Cross.Street.2,
Intersection.Street.2,
"X.Coordinate.(State.Plane)",
"Y.Coordinate.(State.Plane)"))
df1 <- data1 %>% select(-starts_with("School"))
df2 <- df1 %>% select(-c(Vehicle.Type:Ferry.Terminal.Name))
trimmed_nyc311 <- df2 %>% select(-contains("Facility"))
rm(my_data, data1, df1, df2)
```
The trimmed dataset showing the first few rows.
```{r trimmed-data, results="hide"}
library(devtools)
library(pander)
#pander(head(trimmed_nyc311))
landscape(knitr::kable(trimmed_nyc311[1:10, 1:18], caption = "Trimmed NYC311 Dataset Display") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
```
```{r nyc-total_NAs, message=FALSE,warning=FALSE, results="hide", eval=FALSE}
#Column Names for the Dataset
colSums(is.na(trimmed_nyc311))
```
*Checking and Removing Rows with high number of NAs*
```{r nyc-na-checks, message=FALSE,warning=FALSE, results="hide"}
colnames(trimmed_nyc311)[colnames(trimmed_nyc311) == 'Resolution.Action.Updated.Date'] <- 'Closeout.Date'
sum(!is.na(trimmed_nyc311$Created.Date))
```
```{r nyc-column-names}
colnames(trimmed_nyc311)
```
**Step 3. Data Cleaning, Enriching and validation: Processing data in selected columns**
*3.1. Cleaning up the Boroughs Column and Removing the "Unspecified" Column*
The Boroughs Column has many values indicating as "Unspecified". We shall try to improve this column below.
```{r}
tapply(trimmed_nyc311$Borough,trimmed_nyc311$Borough,length)
```
```{r results="hide"}
df1_Bor <- trimmed_nyc311 %>%
select(Unique.Key,
Created.Date,
Closed.Date,
Agency,
Complaint.Type,
Incident.Zip,
Borough,
Status,
Closeout.Date,
Latitude,
Longitude)
#head(df1_Bor, 20)
landscape(knitr::kable(df1_Bor[1:10, 1:11], caption = "Data Before Cleaning") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
```
*3.2. Select only data with Unspecified Values*
```{r}
# Remove null & NA values
df1_Boroughs <- df1_Bor[!is.na(df1_Bor$Incident.Zip) & df1_Bor$Incident.Zip !="" &df1_Bor$Borough=="Unspecified"]
#head(df1_Boroughs)
#nrow(df1_Boroughs)
```
*3.3. Using the ZipCode dataset to replace matching Borough values.*
```{r nycZipCode_data}
#Load ZipCode Data
nycZipCodes <- fread("zipbyboro.csv")
knitr::kable(head(nycZipCodes)) %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 11)
```
```{r}
#Matching ZipCodes from both datasets
zipValue <- match(df1_Boroughs$Incident.Zip,nycZipCodes$zip, nomatch = 0)
```
```{r}
df1_Boroughs$Borough[zipValue !=0] <- nycZipCodes$borough[zipValue]
```
```{r}
#Changing the Initial Dataset to correct unavailable values with real Boroughs Names
# Requires library(plyr)
zipValue <- match(trimmed_nyc311$Unique.Key, df1_Boroughs$Unique.Key, nomatch = 0)
trimmed_nyc311$Borough[zipValue !=0] <- df1_Boroughs$Borough[zipValue]
BoroughSummarytotal <- ddply(df1_Boroughs, c( "Borough"), summarise, N = length(Borough))
```
*3.4. Results after matching Zipcodes in both datasets*
```{r}
tapply(trimmed_nyc311$Borough,trimmed_nyc311$Borough,length)
```
>Observation: The "Unspecified" values in the Borough Column are now reduced substatialy.
```{r eval= FALSE, results="hide"}
describe(trimmed_nyc311$Borough)
```
*3.5. Checking For Duplicate Rows "AFTER" dropping the "Unique.Key" ID using DISTINCT Keyword*
*Note:* There are very few duplicate rows when inspected with the "Unique.Key" column, but after dropping the Unique.Key column, we now realized we had over a million duplicates.We shall therefore based our analysis from hence on the "nyc311nodups" column.
```{r nyc_no_dups1, results="hide"}
if (!require(dplyr)) {
install.packages("dplyr",dependencies=TRUE)
library(dplyr)
}
nyc311nodups<-distinct(trimmed_nyc311)
all_equal(nyc311nodups,trimmed_nyc311)
nrow(trimmed_nyc311)
nrow(nyc311nodups)
#rm(trimmed_nyc311)
#gc()
```
**Step 4. Data Analysis & Reporting**
*Visualization BEFORE AND AFTER Borough Column Improvement*
- Call Distribution by Borough
```{r nyc311Plot_2A, message=FALSE,warning=FALSE}
nyc311 %>%
dplyr::group_by(Borough) %>%
filter(!is.na(Borough)) %>%
dplyr::summarise(Count = dplyr::n()) %>%
ungroup() %>%
mutate(Borough = reorder(Borough,Count)) %>%
arrange(desc(Count)) %>%
head(10) %>%
ggplot(aes(x = Borough,y = Count)) +
geom_bar(stat='identity',
colour="white",
fill = fillColor3) +
geom_text(aes(x = Borough,
y = 1,
label = paste0("(",Count,")",
sep="")),
hjust=0.5, vjust=-2.5, size = 4, colour = 'black',
fontface = 'bold') +
labs(x = 'Borough',
y = 'Count',
title = 'Number of Complaints By Borough"before Borough Col improved') +
theme_bw()
```
- *Call Distribution by County (After Boroughs Col Improvement)*
```{r nyc311Plot_2B, message=FALSE,warning=FALSE}
nyc311nodups %>%
dplyr::group_by(Borough) %>%
filter(!is.na(Borough)) %>%
dplyr::summarise(Count = dplyr::n()) %>%
ungroup() %>%
mutate(Borough = reorder(Borough,Count)) %>%
arrange(desc(Count)) %>%
head(10) %>%
ggplot(aes(x = Borough,y = Count)) +
geom_bar(stat='identity',
colour="white",
fill = fillColor4) +
geom_text(aes(x = Borough,
y = 1,
label = paste0("(",Count,")",
sep="")),
hjust=0.5, vjust=-2.5, size = 4, colour = 'black',
fontface = 'bold') +
labs(x = 'Borough',
y = 'Count',
title = 'Number of Complaints By Borough "after borough col improved"') +
theme_bw()
```
>Observation shows that The Unspecified values under Boroughs reduced in number from 1,059,265 to 238,883 overall. A reduction factor of over 4 times.
```{r}
rm(nyc311)
```
**Processing Dates.**
Inorder to perform date calculations such as getting getting the total count of all complaints created in a year, month or week, we need to perform some data transformation on the Date columns. The raw data is in character format which does not support any date calculations. The lubridate package helps us do the automatic conversions to calendar and local time formats.
Upon inspection, the following issues were noted;
1. Dates in char format; To be converted to Date format
2. Given dates are in the 12 Hour %m/%d/%Y %H:%M:%S %p format; To be converted to POSIXct format
3. There were missing dates, others without the AM or PM notation
4. There were outliers such as 01/01/1900 and 12/31/2037 in the system
Here are the steps taken in resolving the mentioned data issues.
**Step 1: Selecting and Setting Date Range to remove Outliers; Dates before year 2010**
We have seen from our plot above, we have dates as far bar as 1900. The following date range confirms this.
*Date Ranges for "Created.Date" Column*
```{r nyc_period_range1, echo= TRUE, message=FALSE,warning=FALSE}
#Range of Dates MinMax in Dataset
range(nyc311nodups$Created.Date, na.rm = TRUE)
```
*Date Ranges for "Closed.Date" Column*
```{r nyc_period_range2, echo= TRUE, message=FALSE,warning=FALSE}
#Range of Dates MinMax in Dataset
range(nyc311nodups$Closed.Date, na.rm = TRUE)
```
*Date Ranges for "Closeout.Date" Column*
```{r nyc_period_range3, echo= TRUE, message=FALSE,warning=FALSE}
#Range of Dates MinMax in Dataset
range(nyc311nodups$Closeout.Date, na.rm = TRUE)
```
> **NOTE:** We shall have to intially drop these values before 2010 start date and any date after December 2015.
**Steps 2: Dropping Date Columns without the AM or PM notation**
```{r nyc_regEx_filter_dates, message=FALSE,warning=FALSE, results="hide"}
library(data.table)
nyc311nodups_1 <- nyc311nodups %>%
select(Unique.Key,
Created.Date,
Closed.Date,
Agency,
Complaint.Type,
Incident.Zip,
Borough,
Status,
Closeout.Date,
Latitude,
Longitude)
#Cleaning up wrong Date formats type in without the AM or PM notation
nyc311nodups_2 <- nyc311nodups_1[grep("[0-9]{2}[[:punct:]][0-9]{2}[[:punct:]]
[0-9]{4}[[:space:]][0-9]{2}[[:punct:]]
[0-9]{2}[[:punct:]][0-9]{2}[[:punct:]][[A-Z]]",
c(nyc311nodups_1$Created.Date,
nyc311nodups_1$Closed.Date,
nyc311nodups_1$Closeout.Date),
invert = TRUE),]
#head(nyc311nodups_2, 20)
landscape(knitr::kable(nyc311nodups_2[1:10, 1:11], caption = "Data Columns With Missing AM, PM Notation Dropped") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
```
```{r}
# Remove null & NA values
yx <- nyc311nodups_2[!(is.na(nyc311nodups_2$Created.Date) | nyc311nodups_2$Created.Date=="" | is.na(nyc311nodups_2$Closed.Date) | nyc311nodups_2$Closed.Date==""|is.na(nyc311nodups_2$Closeout.Date) | nyc311nodups_2$Closeout.Date==""),]
```
Number of Rows and Range of Dates After Removing NAs
```{r}
#Range of Dates MinMax in Dataset
range(yx$Created.Date, na.rm = TRUE)
range(yx$Closed.Date, na.rm = TRUE)
range(yx$Closeout.Date, na.rm = TRUE)
```
> Observation: There are erroneous dates such as "01/01/1900 12:00:00 AM" that need to be removed.
*Selecting Date Range to avoid outliers*
```{r}
a1 <- yx[Created.Date >= "01/01/2010" & Created.Date <= "12/31/2014"]
#head(a1)
```
**Step 3 & 4: Converting String format into Date format using as.POSIXct if neccessarry and Date Filter**
This will be done inside the code as we plot the trends with filters as follows:
1. "!is.na" To remove NAs
2. Using "as.POSIXct" or "mdy:HMS" methods from the Lubridate function to convert dates into workable formats
3. Select Date range with "scale_x_date" method from the Scales R package
```{r eval=FALSE}
class(a1$Created.Date)
```
*Parse strings and Convert to Date and Time*
```{r}
new_NYC311_Data <- a1
new_NYC311_Data$Created.Date <- as.POSIXct(strptime(a1$Created.Date,format = "%m/%d/%Y %H:%M:%S %p"), "America/New_York")
new_NYC311_Data$Closed.Date <- as.POSIXct(strptime(a1$Closed.Date,format = "%m/%d/%Y %H:%M:%S %p"), "America/New_York")
new_NYC311_Data$Closeout.Date <- as.POSIXct(strptime(a1$Closeout.Date,format = "%m/%d/%Y %H:%M:%S %p"), "America/New_York")
```
```{r results="hide"}
class(new_NYC311_Data$Created.Date)
class(new_NYC311_Data$Closed.Date)
class(new_NYC311_Data$Closeout.Date)
```
Cleaned Date Formats after formating
```{r}
#head(!is.na(new_NYC311_Data$Created.Date))
#head(new_NYC311_Data$Created.Date)
```
```{r}
#head(new_NYC311_Data)
knitr::kable(head(new_NYC311_Data)) %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7)
```
### 3.2 The NYC Department of Buildings Dataset
**i. Introducing The New York City Department of Building Dataset**
This is repository of complaints received by Department of Buildings (DOB). It includes complaints that come from 311 or that are entered into the system by DOB staff.
The dataset dimensions is as follows:
Rows 2.53M
Columns 15
This dataset covers all the five boroughs of NewYork City and a record of complaints related to buildings classified into coded categories. This complaint Categories codes can be found at
[Complaints Category](http://www1.nyc.gov/assets/buildings/pdf/bis_complaint_disposition_codes.pdf)
The pdf table file was converted to a csv file format and loaded for use.
**ii. Data Wrangling Process For Dataset 2**
The following steps are used in the process of data discovery and data cleaning for the new dataset as well.
i. Loading New Dataset
ii. Loading New Dataset
iii.Data Discovery - checking summaries and counts
iv. Removing duplicates
v. Data Cleaning
**iii. Loading The New NYC Department of Building Dataset**
```{r DoB_raw_data1, message=FALSE}
if (!require(data.table)) {
install.packages("data.table",dependencies=TRUE)
library(data.table)
}
nycDoB<-fread("DoB_NYC_sample.csv", stringsAsFactors = FALSE)
names(nycDoB)<-names(nycDoB) %>%
stringr::str_replace_all("\\s", ".")
```
Initially we load "DoB_NYC_sample.csv" file for testing purposes then later we revert to the full "DoB_NYC.csv" dataset for complete analysis.
**iv. Cleaning & Exploratory Data Analysis**
The Department of Housing and Preservation Dataset has
Column Names for the DoB dataset
```{r columns_in_DoB}
colnames(nycDoB)
```
*Checking for Total Number of rows in our dataset*
```{r}
ncol(nycDoB)
```
The NYC DoB Sample dataset showing the first few rows.
```{r}
library(devtools)
library(pander)
#pander(head(nycDoB))
landscape(knitr::kable(head(nycDoB), caption = "Second Dataset: NYC Department of Building Complaints") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
```
*Checking for duplicates*
```{r message=FALSE,warning=FALSE}
#Checking for how many unique values there are for each column
sapply(nycDoB,function(x) length(unique(x)))
```
*Removing Columns with no data using various methods as outlined below:*
- The DOBRunDate Column shall be removed
- All Duplicate rows removed after data inspection
- NAs for Created Date are removed too
```{r DoB_data_cleaning, message=FALSE,warning=FALSE}
nycDoB_data<- nycDoB
DoB_data1 <-within(nycDoB_data, rm(V1,
DOBRunDate
))
rm(nycDoB_data, nycDoB)
```
*Checking For Duplicate Rows "AFTER" dropping the "Unique.Key" ID using DISTINCT Keyword*
*Note:* There are very few duplicate rows when inspected with the "Unique.Key" column, but after dropping the Unique.Key column, we now realized we had over a million duplicates.We shall therefore based our analysis from hence on the "nyc311nodups" column.
```{r DoB_no_dups3, results="hide"}
if (!require(dplyr)) {
install.packages("dplyr",dependencies=TRUE)
library(dplyr)
}
nycDoBnodups<-distinct(DoB_data1)
all_equal(nycDoBnodups,DoB_data1)
nrow(DoB_data1)
nrow(nycDoBnodups)
rm(DoB_data1)
```
```{r DoB_na-checks2, message=FALSE,warning=FALSE, results="hide"}
#Checking and Removing Rows with high number of NAs
sum(!is.na(nycDoBnodups$Created.Date))
```
```{r DoB_total_NAs, message=FALSE,warning=FALSE, eval=FALSE}
colSums(is.na(nycDoBnodups))
```
**v. Creating Borough Column by Splitting Complaint Number**
The Complaint number format is given as a seven digit number starting with "1000001 ... 1000017" all the way to the last item at 2.5 million. The first digit stands for the Borough code: (1= Manhattan, 2= Bronx, 3 = Brooklyn, 4 = Queens, 5 = Staten Island)
We can therefore do a split of the Complaint Number column and create a Boroughs Column. This is given in the following steps:
*Splitting Complaint Number To Extract Borough digit*
```{r results="hide"}
if (!require(reshape)) {
install.packages("reshape",dependencies=TRUE)
library(reshape)
}
if (!require(qdap)) {
install.packages("qdap",dependencies=TRUE)
library(qdap)
}
library(rJava)
library(reshape)
x <- colSplit(nycDoBnodups$Complaint.Number, col.sep="")
newDoB_Add <- data.frame(ID1=x[, 1], ID2=paste2(x[, 2:7], sep=""),
nycDoBnodups[, -1])
#head(newDoB_Add)
landscape(knitr::kable(head(newDoB_Add), caption = "NYC Department of Building Complaints Dataset") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
#rm(x)
```
Checking Categorical Levels representing the Boroughs
```{r eval=FALSE}
levels(newDoB_Add$ID1)
```
```{r}
# We can now rename the levels
levels(newDoB_Add$ID1) <- c('Manhattan', 'Bronx', 'Brooklyn', 'Queens', 'Staten Island')
# And check the new levels
levels(newDoB_Add$ID1)
```
*Changing names of Variables ID1 & ID2 to Boroughs and Complain.NewNumber*
```{r results="hide"}
colnames(newDoB_Add)[colnames(newDoB_Add) == 'ID1'] <- 'Borough'
colnames(newDoB_Add)[colnames(newDoB_Add) == 'ID2'] <- 'Complaint.NewNumber'
#pander(head(newDoB_Add))
landscape(knitr::kable(head(newDoB_Add), caption = "Changing Colnames of DoB Dataset") %>%
kable_styling(latex_options = c("striped",
"hover",
"responsive"),
full_width = T,
font_size = 7) %>%
column_spec(2,width="6in"))
```