-
Notifications
You must be signed in to change notification settings - Fork 0
/
My-Code_Housing_Price
1712 lines (1352 loc) · 76.5 KB
/
My-Code_Housing_Price
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
install.packages("tidyr")
install.packages("corrplot")
install.packages("reshape2")
install.packages("caret")
install.packages("AppliedPredictiveModeling")
install.packages("stargazer")
install.packages("dplyr")
install.packages("plyr")
install.packages("stringr")
install.packages("lazyeval")
install.packages("hexbin")
install.packages("devtools")
install_github("mrdwabmisc", "mrdwab")
library(plyr)
library(devtools)
library(hexbin)
library(caret)
library(sunflowerplot)
library(lazyeval)
library(stringr)
library(tidyr)
library(corrplot)
library(reshape2)
library(caret)
library(AppliedPredictiveModeling)
library(stargazer)
library(dplyr)
#how to import a file :
library(readr)
BD5TRAIN2_jo2 <- read_csv("/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/BD5TRAIN2_jo2.csv")
View(BD5TRAIN2_jo2)
head(BD5TRAIN)
Violations2 <- Violations %>% separate(Location, c("Lat", "Long"))
Violations2 <- Violations %>% separate(Violations, Location, c("Lat", "Long"), sep = " ", remove = FALSE, convert = TRUE, extra = "warn", fill = "warn",)
Violations2016 <- read.csv("C:/Users/Keisan/Documents/CPLN590/Violations2016.csv", header = TRUE, row.names = NULL)
gsub( "POINT (", "", as.character(Violations$Location) n)
Violations2 <- gsub("C([0-7]+)_.*", "\\1", Violations$Location)
Property <- read.csv("C:/Users/Keisan/DOcuments/CPLN590/MIDTERM/DATA/Propertyfile.csv", header = TRUE, row.names = NULL)
View(Property)
View(Property)
View(Violations)
Violations <- read.csv("C:/Users/Keisan/Downloads/LI_Violations2016.csv", header = TRUE, row.names = NULL)
stringsAsFactors= TRUE,
stringsAsFactors= TRUE,
strip.white = TRUE)
BD5TRAIN2_jo2 <- read.table("C:/Users/Keisan/DOcuments/CPLN590/MIDTERM/DATA/BD5TRAIN2_jo2.csv", header = TRUE, fill = TRUE)
separate(Violations, Location, c("Lat11", "Long11"), sep = " ")
Violationstest2 <- gsub("POINT ", "", Violations$Location)
vlocsplit= gsub("POINT", "", Location)
V4 <- gsub("\\(|\\)", "", V3)
gsub("\\[|\\]", "", n)
View(V4)
V5 <- separate(V4, x, c("Lat11","Long11"), sep = " ")
V5 <- merge(Violations[Violations$year=="2014",], test[test$year=="2015",], by = "p1", all = TRUE)
Violations2 <- Violations + as.data.frame(V4)
dataFrame$newColumn <- dataFrame$oldColumn1 + dataFrame$oldColumn2
LocDataFrame <- (V4 c("Location")))
V4df <- data.frame(as.list(V4))
V4DF <- data.frame(lapply(V4, type.convert), stringsAsFactors=FALSE)
V4DF2 <- data.frame(keyName=names(V4), value=V4, row.names=NULL)
require(reshape2)
Violations$Locations2 <- rownames(V4)
melt(V4)
Violationstest <- Violations
read.table(text=gsub("^[^(]+\(|\)", "", Violations$Location),
header=FALSE, col.names = c("lat", "lon"), stringsAsFactors=FALSE)
Violations = data.frame(Location = "POINT (-7423249 453982)")
Violations$Lat = strsplit(as.character(Violations$Location)," ")[[1]][2]
Violations$Lat = as.numeric(gsub("\\(","",Violations$Lat))
Violations$Lon = strsplit(as.character(Violations$Location)," ")[[1]][3]
Violations$Lon = as.numeric(gsub("\\)","",Violations$Lat))
ViolationsTest <- structure(list(Location = c("POINT (-7423249 453982)",
"POINT (-7412345 453321)"
)), .Names = "Location", row.names = c(NA, -2L), class = "data.frame")
read.table(text=gsub("^[^(]+\(|\)"), "", Violations$Location,
header=FALSE, col.names = c("lat", "lon"), stringsAsFactors=FALSE)
read.table(text=gsub("^[^(]+\\(|\\)", "", ViolationsTest$Location),
header = FALSE, col.names = c("lat", "lon"), stringsAsFactors=FALSE)
ViolationsTest = c("POINT (-7423249 453982)",
"POINT (-7412345 453321)")
lat = as.numeric(gsub("POINT\\s*\\((-?\\d+).*", "\\1", ViolationsTest))
lon = as.numeric(gsub("POINT\\W+\\d+\\s+-?(\\d+).*", "\\1", ViolationsTest))
lat
Villations <- Violations
View(Villations)
V2k16 %>% separate(V2k16$Location, c("Lat", "Long"), " ")
library(stringr)
str_split_fixed(before$type, "_and_", 2)
within(V2k16, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))
separate(V2k16, Location, (Lat + Long), sep = " ")
separate(V2k16,Location, c('Lat', 'Long'), sep = " ")
separate(V2k16, Location, c('Lat', 'Long'))
VVV <- strsplit(V2k16$Location, " ")
separate(V2k16, Location, c('Lat', 'Long'), sep = " ", remove = TRUE, convert = FALSE, extra = "warn", fill = "warn",)
V2k16x <- with(V2k16, data.frame(attr = VVV))
V2k16x <- cbind(V2k16x, data.frame(t(sapply(out, `[`))))
names(after)[2:3] <- paste("type", 1:2, sep = "_")
BD5TRAIN2_jo2 <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/BD5TRAIN2_jo2.csv",header = TRUE , sep = ",")
Near_Retail <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_AllRetail.txt",
header = TRUE)
Near_Retail <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_AllRetail.txt", header = TRUE)
Near_CommCorr <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_CommCorr.txt", header = TRUE , sep = ",")
Near_CrimeInc <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_CrimeInc.txt", header = TRUE , sep = ",")
Near_HighwyExit <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_HighwyExit.txt", header = TRUE , sep = ",")
Near_SeptaStops <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_SeptaStops.txt", header = TRUE , sep = ",")
Near_TrafficData <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_TrafficData.txt", header = TRUE , sep = ",")
Near_Vacant <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_Vacant.txt", header = TRUE , sep = ",")
Near_Violations <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_Violations.txt", header = TRUE , sep = ",")
View (Near_HighwyExit)
View (Near_SeptaStops)
View (Near_TrafficData)
View (Near_Vacant)
View (Near_Violations)
View(Near_Retail)
View(CommCorr)
View(PropertyR)
PropertyR <- read.table("C:/Users/Keisan/Documents/CPLN590/PropertyR.csv", header = TRUE , sep = ",")
Near_Vacant <- Near_Vacant[,-1,]
head(Near_Vacant)
Near_Vacant > subset(Near_Vacant, select=-c(OBJECTID))
BigData1 = merge(Near_Violations, Near_Vacant, by.x=("OBJECTID"), by.y= c("IN_FID", all = TRUE))
head(BigData1)
merged.BIGDATA1.all <- merge(Near_Violations, Near_Vacant, by.x=("OBJECTID"), by.y=c("IN_FID"), all=TRUE)
# edits titles of columns for clarity as dataframe gets bigger
colnames(Near_Vacant) <- paste(colnames(Near_Vacant), "Vac", sep = ".")
colnames(Near_Violations) <- paste(colnames(Near_Violations), "LIViol", sep = ".")
colnames(Near_Retail) <- paste(colnames(Near_Retail), "Retail", sep = ".")
colnames(Near_SeptaStops) <- paste(colnames(Near_SeptaStops), "SeptST", sep = ".")
colnames(Near_TrafficData) <- paste(colnames(Near_TrafficData), "TrafDat", sep = ".")
colnames(Near_HighwyExit) <- paste(colnames(Near_HighwyExit), "HwyEx", sep = ".")
colnames(Near_CommCorr) <- paste(colnames(Near_CommCorr), "ComCor", sep = ".")
#print names to check
colnames(Near_Vacant)
colnames(Near_Violations)
colnames(Near_Retail)
colnames(Near_SeptaStops)
colnames(Near_TrafficData)
colnames(Near_HighwyExit)
colnames(Near_CommCorr)
#substitute in case you made a mistake
names(Near_Vacant) <- gsub("_Vac","",names(Near_Vacant))
head(Near_Vacant)
head(Near_Violations)
#merge 2 dataframes at a time to make one big dataset and keep all records
BigData1 <- merge(x = Near_Vacant, y = Near_CommCorr, by.x = "IN_FID.Vac", by.y = "OBJECTID.ComCor", all = TRUE)
#Keep replacing the 'y' variable and 'by.y' variable names each time
BigData1 <- merge(x = BigData1, y = Near_Violations, by.x = "IN_FID.Vac", by.y = "OBJECTID.LIViol", all = TRUE)
BigData1 <- merge(x = BigData1, y = Near_SeptaStops, by.x = "IN_FID.Vac", by.y = "OBJECTID.SeptST", all = TRUE)
BigData1 <- merge(x = BigData1, y = Near_HighwyExit, by.x = "IN_FID.Vac", by.y = "IN_FID.HwyEx", all = TRUE)
#check the number of columns after each merge. should grow
ncol(BigData1)
colnames(BigData1)
#format BigData1 for only the near_dist fields
Independent_variables <- BigData1 #reassigns dataset for manipulaiton
Near_dist_col <- BigData1 %>% select(starts_with("Near_DIST"))
ncol(Near_dist_col)
head(Near_dist_col)
View(Near_dist_col)
Prop_Ind_Var <- PropertyR %>% select(Zoning,Taxable_Bu,Taxable_La,Depth,Garage_Space,Total_Liva)
#add a new column to eaach data frame
Train85spread[,13] <- NA
Train85spread <- Train85cut
colnames(Train85spread)[13] <- "FID"
#gives empty column numbers
Train85spread$FID <- 1:nrow(Train85spread)
Near_dist_col$FID.Main2 <- 1:nrow(Near_dist_col)
head(Train85spread)
#drop column by number
BD5TRAIN <- BD5TRAIN[,-18]
BigData2 <- merge(x = Prop_Ind_Var, y = Neardist_col, by.x = "FID.Main", by.y = "FID.Main3", all = TRUE)
#add dependent variable to dataframe
DepVar <- PropertyR %>% select(Sale_Pri_1,Field1,Sale_Price,Sale_Year,Lat1,Long1)
DepVar <- PropertyR %>% select(Sale_Pri_1,Field1,Sale_Price,Sale_Year,Lat1,Long1)
#output this as a csv for backup
write.csv(BD5TRAIN, file = "C:/Users/Keisan/Documents/CPLN590/bd5TRAIN_RESULTS.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
######################################################################################
#----------------------------------------Creating Training Dataset-------------------------
#in case you need to reimport BigData3-
BD5TEST2 <- read.csv2("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/BD5TEST.csv", header = TRUE)
#make a copy of course ;)
BD3 <- BigData3
#This dataset has the dependent variable and "most of the independent variables"
TrainingSet1 <- BigData3
BigData3 [,1]
colnames(BigData1 [,1])
#gives column number with name
which( colnames(BigData3)=="random_name" )
#gives column name with number
colnames( BigData3 )[1]
colnames(QTrain175)
TraingingSet1 <- BigData3[,-1] #removes one column from dataframe
QTrain175 <- QTrain175[,-1] #removes column by number
TrainingSet1 <- TrainingSet1[, -c(2:4)] #deletes a series of columns
TrainingSet1 <- TrainingSet1[,-1]
BD5TRAIN[,-1]
View(TrainingSet1)
colnames(TrainingSet1)
training3 <- training[, c(2, 12,10)] # include three other columns
############################################################
#----------------------------------Summary Stats on Dataset--------------------------
stargazer(TrainingSet1, type ="text", title = "Summary Statistics")
stargazer(both, type = "html")
#####################################################################
#Now were going to create a correlation matrix using the corrplot package
TrainingSet1Cpy <- TrainingSet1
TrainingSet1Cpy[is.na(TrainingSet1Cpy)] <- 0
cor(TrainingSet1Cpy, use="pairwise.complete.obs")
TS1C <- cor(TrainingSet1Cpy)
M[is.na(M)] <- 0
TH
head(trainprop3)
TP <- cor(trainprop3)
#returns correlation for each variable to all the others. Here is a pretty correlation matrix plot.
#check the help for corrplot. There are a bunch of different methods for creating these graphics
corrplot(TH, method = "number")
####################################
#----------------------------Quick Training Dataset---------------------
#You just downsized the Dataset so that every value matches up. should've done thisi before.
#nevertheless you now have a lot less data to work with so time to re-import the dataset and
#re do the training|testing partition
Quick_Train <- read.csv2("C:/Users/Keisan/Documents/CPLN590/Quick_Train.csv", header= TRUE)
cutoff = round(0.7*nrow(Quick_Train666))
Train666 <- Quick_Train666
Train666_70cut <- Train666[1:cutoff,]
Test666_30cut <- Train666[-(1:cutoff),]
View(Train666_70cut)
View(Test666_30cut)
# Need to make your dataframes numeric
QuickT_Set <- Quick_train_set #make a copy for safety
colnames(QuickT_Set) #trying to figure out which columns are not numeric
is.numeric(QuickT_Set$Zoning) #f
is.numeric(QuickT_Set$Taxable_La)#f
is.numeric(QuickT_Set$Depth) #f
is.numeric(QuickT_Set$Garage_Spa) #t
is.numeric(QuickT_Set$Total_Liva) #T
is.numeric(QuickT_Set$NEAR_DIST.Vac) #T
is.numeric(QuickT_Set$NEAR_DIST.ComCor) #t
is.numeric(QuickT_Set$NEAR_DIST.SeptaST) #F
is.numeric(QuickT_Set$NEAR_DIST.TrafDat) #T
is.numeric(QuickT_Set$NEAR_DIST.HwyEx) #T
is.numeric(QuickT_Set$Sale_Pri_1) #T
transform(TrainingSet2, NEAR_DIST.SeptaST = as.numeric(NEAR_DIST.SeptaST))
#Remove all $ in these columns "Taxable_Bu" & "Taxable_La"
gsub("$", "", QTrain175$Depth)
head(BD3$Taxable_La)
#what mode
mode(TrainingSet2$NEAR_DIST.SeptaST)
#####
# The droids you are looking for aka. the variables you wanna do regression on
#"Depth" "Garage_Spa" "Total_Liva" "NEAR_DIST.Vac"
#[5] "NEAR_DIST.ComCor" "NEAR_DIST.LIViol" "NEAR_DIST.Retail" "NEAR_DIST.SeptST"
#[9] "NEAR_DIST.TrafDat" "NEAR_DIST.HwyEx" "Sale_Pri_1" "Tax_Build"
#[13] "Tax_Land"
#But one better! - Output this as backup just incase.
write.csv(Quick_Train, file = "C:/Users/Keisan/Documents/CPLN590/Quick_Train.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
write.csv(Quick_Test, file = "C:/Users/Keisan/Documents/CPLN590/Quick_Test.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
stargazer(QTrain70, type="text", title = "Summary Statistics")
View(QTrain70)
str(QTrain70)
head(QTrain70)
#Assign factors as integers
Train85cut$NEAR_DIST.Retail <- as.integer(as.character(Train85cut$NEAR_DIST.Retail))
#Do it for all factoral columns
Train85cut$NEAR_DIST.ComCor <- as.integer(as.character(Train85cut$NEAR_DIST.ComCor))
Train85cut$NEAR_DIST.SeptST <- as.integer(as.character(Train85cut$NEAR_DIST.SeptST))
Train85cut$NEAR_DIST.Vac <- as.integer(as.character(Train85cut$NEAR_DIST.Vac))
Train85cut$NEAR_DIST.LIViol <- as.integer(as.character(Train85cut$NEAR_DIST.LIViol))
Train85cut$NEAR_DIST.TrafDat <- as.integer(as.character(Train85cut$NEAR_DIST.TrafDat))
Train85cut$NEAR_DIST.HwyEx <- as.integer(as.character(Train85cut$NEAR_DIST.HwyEx))
#format summary statistics output
stargazer(OLS_1, type="text", title = "Summary Statistics") #basic
stargazer(OLS_1, type = "text", nobs = FALSE, mean.sd = TRUE, median = TRUE,
+ iqr = TRUE) #more information in charts
stargazer(QTrain70, type = "text", style = "qje") #style difference
stargazer(OLS_1, type = "text",
title = "Summary Statistics",
covariate.labels = c("Garage Space Dimension", "Total Livable Space", "Dist.to Vacancy",
"Nearest Commercial Corridor", "Nearest LI Violation", "Nearest Retail",
"Nearest Septa Stop", "Nearby Traffic Density", "Nearest Highway Exit", "Sale Price", "Building Tax","Land Tax"),
dep.var.caption = "Dependent Variable",
dep.var.labels = "Sale Price") #rename independent labels
stargazer(QTrain70, type = "text",
dep.var.labels.include = FALSE,
model.numbers = FALSE) #not interested in this
##########################################################################
#running a OLS Regression on the dataset
colnames(QTrain70)notepad
########################################## Runs a regression ###############################!!!!!!!!!!!!!!!!!!
N_hood <- lm(Sale_Pri_1 ~ Garage_Spa + Total_Liva + NEAR_DIST_Vac + NEAR_DIST_ComCor + NEAR_DIST_LIViol + NEAR_DIST_Retail + NEAR_DIST_SeptST + NEAR_DIST_TrafDat + NEAR_DIST_HwyEx + Tax_Build + Tax_Land, data = BD6_Neighb_Jo)
### make dataset smaller
cutoff = round(0.7*nrow(BD5))
QTrain175 <- QTrain35
BD5TRAIN <- BD5[1:cutoff,]
BD5TEST <- BD5[-(1:cutoff),]
dim(BD5TRAIN)
#regression ran after you subsetted the data twice. Hooray! you have some data to plot visualizations
#based on! this is the main point.
#Now just output that file for safety reasons...
write.csv(BD5TRAIN, file = "C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/BD5TRAIN.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "") #cant cuz itsaves as a character not a data.frame and cannot be
#coerced into a data.frame
View(OLS_1) #can't view it saves as a function
#summary of OLS_1
summary(OLS_1)
library(corrplot)
cor(Train85cut) #produces correlation coefficients in list
TR85cut <- cor(Train85cut)
#Now to visualize
corrplot.mixed(TR85cut, order ="AOE",method ="color",addCoef.col="grey") #not working :(
#if column has null values in them
QMat[is.na(Qmat)] <- 0
#pairwise obs
QTMat <- QtestMatrix
cor(QtestMatrix, use="pairwise.complete.obs")
corrplot(BD5TRAIN, method = "number")
#subsetted data with. Now to go through previous steps with reformatting and subsetting
Quick_Train666 <- na.omit(Quick_Train)
Train666 <- Quick_Train666
Train666_70cut <- Train666[1:cutoff,]
is.numeric(Train85cut$NEAR_DIST.LIViol)
#rmse, rse, etc for training set
#now the mean residual or error from the regression 'reg' aka the 'mean absolute error' aka the MAE
mean(abs(Train85cut$Sale_Pri_1))
#calculate the MAPE - or mean absolute percent error aka MAPE
mean(abs(Train85cut$Sale_Pri_1))
#plot variation in regression output
x <- rnorm(1000)
y <- rnorm(1000)
bin<-hexbin(x, y, xbins=50)
plot(bin, main="Hexagonal Binning")
hexbin(Train85cut)
#stylize the corrplot:
col1 <- colorRampPalette(c("#7F0000","red","#FF7F00","yellow","white",
"cyan", "#007FFF", "blue","#00007F"))
col2 <- colorRampPalette(c("#67001F", "#B2182B", "#D6604D", "#F4A582", "#FDDBC7",
"#FFFFFF", "#D1E5F0", "#92C5DE", "#4393C3", "#2166AC", "#053061"))
col3 <- colorRampPalette(c("red", "white", "blue"))
col4 <- colorRampPalette(c("#7F0000","red","#FF7F00","yellow","#7FFF7F",
"cyan", "#007FFF", "blue","#00007F"))
wb <- c("white","black")
corrplot(Train85cut, method="square", order = "FPC", cl.pos="n") #corrplot of Train85cut OLS output, using squares, First Class Principle, no color ramp legend,
head(Train85cut)
#this works for corrplot
corrplot(cor(Train85cut), method="square", order = "FPC", cl.pos="n", p.mat = res1[[1]], sig.level = 0.02, insig = c("p-value"))
pAdj <- p.adjust(c(res1[[1]]), method = "BH")
###select specific columns and drop them
Train85cut2> subset(Train85cut, select=-c(Train85cut,Near_DIST.TrafDat))
R> subset(df, select=-c(z,u))
############## CORRELATION OUTPUT with significance levels indicated by an "X"
cor.mtest <- function(mat, conf.level = 0.95){
mat <- as.matrix(mat)
n <- ncol(mat)
p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n)
diag(p.mat) <- 0
diag(lowCI.mat) <- diag(uppCI.mat) <- 1
for(i in 1:(n-1)){
for(j in (i+1):n){
tmp <- cor.test(mat[,i], mat[,j], conf.level = conf.level)
p.mat[i,j] <- p.mat[j,i] <- tmp$p.value
lowCI.mat[i,j] <- lowCI.mat[j,i] <- tmp$conf.int[1]
uppCI.mat[i,j] <- uppCI.mat[j,i] <- tmp$conf.int[2]
}
}
return(list(p.mat, lowCI.mat, uppCI.mat))
}
res1 <- cor.mtest(mtcars,0.95)
res2 <- cor.mtest(mtcars,0.99)
## specialized the insignificant value according to the significant level
corrplot(M, p.mat = res1[[1]], sig.level=0.2)
######################## RMSE
summary(Train85cut)
lm(formula = Sale_Pri_1 ~ Garage_Spa + NEAR_DIST.LIViol + NEAR_DIST.Retail, data = Train85cut)
CV <- CVlm(data=trainhouse5, CVT, m=8)
exists("fit")
#m=5 sets it to 5 folds
mse <- attr(CVT, "ms")
rmse <- sqrt(mse) #Obtaining RMSE for model 1
rmse
#Now were going to see how generalizable some of these ind. variables are across both Starbucks and Dunkin Donuts.
#The following lines of code do the same thing as above to create the 'training2' data frame but this time using
#only Starbucks and Dunkin Donuts locations.
#Create a new data frame of just starbucks and DD locations
StarbucksOrDunkin <- biz[ which(biz$CONAME == "DUNKIN' DONUTS" | biz$CONAME == "STARBUCKS" ), ]
#create a dummy variablefor DD
StarbucksOrDunkin$isDunkin = ifelse(StarbucksOrDunkin$CONAME == "DUNKIN' DONUTS" ,1,0)
#create a new data frame of just the important variables.
SD2 <- StarbucksOrDunkin[,22:40] #create a new data frame of most of the ind. variables
SD2 <- SD2[,-5] #removes one column from that
SD3 <- StarbucksOrDunkin[, c(12,10)] # install.packages("tidyr")
install.packages("corrplot")
install.packages("reshape2")
install.packages("caret")
install.packages("AppliedPredictiveModeling")
install.packages("stargazer")
install.packages("dplyr")
install.packages("stringr")
install.packages("lazyeval")
install.packages("hexbin")
install.packages("ggplot2")
library(hexbin)
library(car)
library(sunflowerplot)
library(lazyeval)
library(stringr)
library(tidyr)
library(corrplot)
library(reshape2)
library(caret)
library(AppliedPredictiveModeling)
library(stargazer)
library(dplyr)
BD5TEST2 <- read.csv2("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/BD5TEST.csv",
header= FALSE)
Violations2 <- Violations %>% separate(Location, c("Lat", "Long"))
Violations2 <- Violations %>% separate(Violations, Location, c("Lat", "Long"), sep = " ", remove = FALSE, convert = TRUE, extra = "warn", fill = "warn",)
Violations2016 <- read.csv("C:/Users/Keisan/Documents/CPLN590/Violations2016.csv", header = TRUE)
gsub( "POINT (", "", as.character(Violations$Location) n)
Violations2 <- gsub("C([0-7]+)_.*", "\\1", Violations$Location)
BD5TEST2 <- read.csv("C:/Users/Keisan/DOcuments/CPLN590/MIDTERM/DATA/BD5TEST.csv", header = TRUE, row.names = )
View(Property)
View(Property)
View(Violations)
Violations <- read.csv("C:/Users/Keisan/Downloads/LI_Violations2016.csv", header = TRUE, row.names = NULL)
stringsAsFactors= TRUE,
stringsAsFactors= TRUE,
strip.white = TRUE)
Property <- read.table("C:/Users/Keisan/DOcuments/CPLN590/MIDTERM/DATA/Propertyfile.csv", header = TRUE, fill = TRUE)
separate(Violations, Location, c("Lat11", "Long11"), sep = " ")
Violationstest2 <- gsub("POINT ", "", Violations$Location)
vlocsplit= gsub("POINT", "", Location)
V4 <- gsub("\\(|\\)", "", V3)
gsub("\\[|\\]", "", n)
View(V4)
V5 <- separate(V4, x, c("Lat11","Long11"), sep = " ")
V5 <- merge(Violations[Violations$year=="2014",], test[test$year=="2015",], by = "p1", all = TRUE)
Violations2 <- Violations + as.data.frame(V4)
dataFrame$newColumn <- dataFrame$oldColumn1 + dataFrame$oldColumn2
LocDataFrame <- (V4 c("Location")))
V4df <- data.frame(as.list(V4))
V4DF <- data.frame(lapply(V4, type.convert), stringsAsFactors=FALSE)
V4DF2 <- data.frame(keyName=names(V4), value=V4, row.names=NULL)
require(reshape2)
Violations$Locations2 <- rownames(V4)
melt(V4)
Violationstest <- Violations
read.table(text=gsub("^[^(]+\(|\)", "", Violations$Location),
header=FALSE, col.names = c("lat", "lon"), stringsAsFactors=FALSE)
Violations = data.frame(Location = "POINT (-7423249 453982)")
Violations$Lat = strsplit(as.character(Violations$Location)," ")[[1]][2]
Violations$Lat = as.numeric(gsub("\\(","",Violations$Lat))
Violations$Lon = strsplit(as.character(Violations$Location)," ")[[1]][3]
Violations$Lon = as.numeric(gsub("\\)","",Violations$Lat))
ViolationsTest <- structure(list(Location = c("POINT (-7423249 453982)",
"POINT (-7412345 453321)"
)), .Names = "Location", row.names = c(NA, -2L), class = "data.frame")
read.table(text=gsub("^[^(]+\(|\)"), "", Violations$Location,
header=FALSE, col.names = c("lat", "lon"), stringsAsFactors=FALSE)
read.table(text=gsub("^[^(]+\\(|\\)", "", ViolationsTest$Location),
header = FALSE, col.names = c("lat", "lon"), stringsAsFactors=FALSE)
ViolationsTest = c("POINT (-7423249 453982)",
"POINT (-7412345 453321)")
lat = as.numeric(gsub("POINT\\s*\\((-?\\d+).*", "\\1", ViolationsTest))
lon = as.numeric(gsub("POINT\\W+\\d+\\s+-?(\\d+).*", "\\1", ViolationsTest))
lat
Villations <- Violations
View(Villations)
V2k16 %>% separate(V2k16$Location, c("Lat", "Long"), " ")
library(stringr)
str_split_fixed(before$type, "_and_", 2)
within(V2k16, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))
separate(V2k16, Location, (Lat + Long), sep = " ")
separate(V2k16,Location, c('Lat', 'Long'), sep = " ")
separate(V2k16, Location, c('Lat', 'Long'))
VVV <- strsplit(V2k16$Location, " ")
separate(V2k16, Location, c('Lat', 'Long'), sep = " ", remove = TRUE, convert = FALSE, extra = "warn", fill = "warn",)
V2k16x <- with(V2k16, data.frame(attr = VVV))
V2k16x <- cbind(V2k16x, data.frame(t(sapply(out, `[`))))
names(after)[2:3] <- paste("type", 1:2, sep = "_")
BD5TEST2 <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/BD5TEST.csv",header = TRUE , sep = ",")
Near_Retail <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_AllRetail.txt",
header = TRUE)
Near_Retail <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_AllRetail.txt", header = TRUE)
Near_CommCorr <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_CommCorr.txt", header = TRUE , sep = ",")
Near_CrimeInc <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_CrimeInc.txt", header = TRUE , sep = ",")
Near_HighwyExit <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_HighwyExit.txt", header = TRUE , sep = ",")
Near_SeptaStops <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_SeptaStops.txt", header = TRUE , sep = ",")
Near_TrafficData <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_TrafficData.txt", header = TRUE , sep = ",")
Near_Vacant <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_Vacant.txt", header = TRUE , sep = ",")
Near_Violations <- read.table("C:/Users/Keisan/Documents/CPLN590/MIDTERM/DATA/Near_Violations.txt", header = TRUE , sep = ",")
View (Near_HighwyExit)
View (Near_SeptaStops)
View (Near_TrafficData)
View (Near_Vacant)
View (Near_Violations)
View(Near_Retail)
View(CommCorr)
View(PropertyR)
PropertyR <- read.table("C:/Users/Keisan/Documents/CPLN590/PropertyR.csv", header = TRUE , sep = ",")
Near_Vacant <- Near_Vacant[,-1,]
head(Near_Vacant)
Near_Vacant > subset(Near_Vacant, select=-c(OBJECTID))
BigData1 = merge(Near_Violations, Near_Vacant, by.x=("OBJECTID"), by.y= c("IN_FID", all = TRUE))
head(BigData1)
merged.BIGDATA1.all <- merge(Near_Violations, Near_Vacant, by.x=("OBJECTID"), by.y=c("IN_FID"), all=TRUE)
# edits titles of columns for clarity as dataframe gets bigger
colnames(Near_Vacant) <- paste(colnames(Near_Vacant), "Vac", sep = ".")
colnames(Near_Violations) <- paste(colnames(Near_Violations), "LIViol", sep = ".")
colnames(Near_Retail) <- paste(colnames(Near_Retail), "Retail", sep = ".")
colnames(Near_SeptaStops) <- paste(colnames(Near_SeptaStops), "SeptST", sep = ".")
colnames(Near_TrafficData) <- paste(colnames(Near_TrafficData), "TrafDat", sep = ".")
colnames(Near_HighwyExit) <- paste(colnames(Near_HighwyExit), "HwyEx", sep = ".")
colnames(Near_CommCorr) <- paste(colnames(Near_CommCorr), "ComCor", sep = ".")
#print names to check
colnames(Near_Vacant)
colnames(Near_Violations)
colnames(Near_Retail)
colnames(Near_SeptaStops)
colnames(Near_TrafficData)
colnames(Near_HighwyExit)
colnames(Near_CommCorr)
#substitute in case you made a mistake
names(Near_Vacant) <- gsub("_Vac","",names(Near_Vacant))
head(Near_Vacant)
head(Near_Violations)
#merge 2 dataframes at a time to make one big dataset and keep all records
BigData1 <- merge(x = Near_Vacant, y = Near_CommCorr, by.x = "IN_FID.Vac", by.y = "OBJECTID.ComCor", all = TRUE)
#Keep replacing the 'y' variable and 'by.y' variable names each time
BigData1 <- merge(x = BigData1, y = Near_Violations, by.x = "IN_FID.Vac", by.y = "OBJECTID.LIViol", all = TRUE)
BigData1 <- merge(x = BigData1, y = Near_SeptaStops, by.x = "IN_FID.Vac", by.y = "OBJECTID.SeptST", all = TRUE)
BigData1 <- merge(x = BigData1, y = Near_HighwyExit, by.x = "IN_FID.Vac", by.y = "IN_FID.HwyEx", all = TRUE)
#check the number of columns after each merge. should grow
ncol(BigData1)
colnames(BigData1)
#format BigData1 for only the near_dist fields
Independent_variables <- BigData1 #reassigns dataset for manipulaiton
Near_dist_col <- BigData1 %>% select(starts_with("Near_DIST"))
ncol(Near_dist_col)
head(Near_dist_col)
View(Near_dist_col)
Prop_Ind_Var <- PropertyR %>% select(Zoning,Taxable_Bu,Taxable_La,Depth,Garage_Space,Total_Liva)
#add a new column to eaach data frame
Train85spread[,13] <- NA
Train85spread <- Train85cut
colnames(Train85spread)[13] <- "FID"
#gives empty column numbers
Train85spread$FID <- 1:nrow(Train85spread)
Near_dist_col$FID.Main2 <- 1:nrow(Near_dist_col)
head(Train85spread)
#drop column by number
Neardist_col <- Near_dist_col[,-8]
BigData2 <- merge(x = Prop_Ind_Var, y = Neardist_col, by.x = "FID.Main", by.y = "FID.Main3", all = TRUE)
#add dependent variable to dataframe
DepVar <- PropertyR %>% select(Sale_Pri_1,Field1,Sale_Price,Sale_Year,Lat1,Long1)
DepVar <- PropertyR %>% select(Sale_Pri_1,Field1,Sale_Price,Sale_Year,Lat1,Long1)
#output this as a csv for backup
write.csv(BigData3, file = "C:/Users/Keisan/Documents/CPLN590/BigData3.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
######################################################################################
#----------------------------------------Creating Training Dataset-------------------------
#in case you need to reimport BigData3-
> BigData3 <- read.csv2("C:/Users/Keisan/Documents/CPLN590/BigData3.csv", header = TRUE)
#make a copy of course ;)
BD3 <- BigData3
ncol(BD3)
colnames(BD3)
#This dataset has the dependent variable and "most of the independent variables"
TrainingSet1 <- BigData3
BigData3 [,1]
colnames(BigData1 [,1])
#gives column number with name
which( colnames(BigData3)=="random_name" )
#gives column name with number
colnames( BigData3 )[1]
colnames(QTrain175)
TraingingSet1 <- BigData3[,-1] #removes one column from dataframe
QTrain175 <- QTrain175[,-1] #removes column by number
TrainingSet1 <- TrainingSet1[, -c(2:4)] #deletes a series of columns
TrainingSet1 <- TrainingSet1[,-1]
View(TrainingSet1)
colnames(TrainingSet1)
colnames(BD3)
na.omit(BD3)
BD3_2 <-BD3
training3 <- training[, c(2, 12,10)] # include three other columns
############################################################
#----------------------------------Summary Stats on Dataset--------------------------
stargazer(TrainingSet1, type ="text", title = "Summary Statistics")
stargazer(both, type = "html")
#####################################################################
#Now were going to create a correlation matrix using the corrplot package
TrainingSet1Cpy <- TrainingSet1
BD5TRAIN[is.na(BD5TRAIN)] <- 0
cor(BD5TRAIN, use="pairwise.complete.obs")
CorBD5train <- cor(BD5TRAIN)
M[is.na(M)] <- 0
TH
na.omit(Quick_Train) #removes na rows.
head(trainprop3)
TP <- cor(trainprop3)
#returns correlation for each variable to all the others. Here is a pretty correlation matrix plot.
#check the help for corrplot. There are a bunch of different methods for creating these graphics
corrplot(CorBD5train, method = "square")
####################################
#----------------------------Quick Training Dataset---------------------
#You just downsized the Dataset so that every value matches up. should've done thisi before.
#nevertheless you now have a lot less data to work with so time to re-import the dataset and
#re do the training|testing partition
table(is.na(Quick_Train))
Quick_Train <- read.csv2("C:/Users/Keisan/Documents/CPLN590/Quick_Train.csv", header= TRUE)
cutoff = round(0.7*nrow(DupBD5))
Train666 <- Quick_Train666
#Let's see if any of this predictive variation is spatial in nature. To do this, were going to have to map these
#predictions in ArcGIS.
#First create a dataframe of the predicted values and the FID which we can join back to the shapefile in ArcGIS
predForArcGIS <- cbind(trainhouse$X, CVT$fitted.values)
summary(BD5ols)
#created test and training sets
BD5train <- DupBD5[1:cutoff,]
BD5Testpool <- DupBD5[-(1:cutoff),]
# Run OLS on Training set
Rittenhouse_ols <- lm(Sale_Pri_1 ~ Garage_Spa + Total_Liva + NEAR_DIST_Vac + NEAR_DIST_ComCor + NEAR_DIST_LIViol + NEAR_DIST_Retail + NEAR_DIST_SeptST + NEAR_DIST_TrafDat + NEAR_DIST_HwyEx + Tax_Build + Tax_Land, data = Rittenhouse, na.action=na.omit)
##################################RMSE & MAE for residuals in BD5ols #############################
# Calculate error
error <- actual - predicted
actual <- resid(BD5ols)
predicted <- predict(BD5ols)
# Function that returns Root Mean Squared Error
rmse <- function(error) ##fuckthis
{
sqrt(mean(error^2))
}
RMSE <- sqrt(mean((y_hat-predict(BD5ols))^2))
############################////////////////////// hey look! its your fItTeD vAlUes
y_hat <- fitted.values(BD5ols)
#and your em ay eee (MAE)
dim(BD5TRAIN)
mae(sim,obs)
MAE <- sum(abs(y_hat-predict)) / length(y_hat)
data(cars)
reg <- lm(log(dist) ~ log(speed), data = cars)
MAPE(y_pred = exp(BD5ols$fitted.values), y_true = BD5train$Sale_Pri_1)
#lets take a closer look at the model error.
#first what is the mean SALES_VOL
mean(BD5TRAIN$Sale_Pri_1)
#calculate the difference and percent change between observed and predicted
BD5TRAIN$diff <- regPredStarbucksValues$obs - regPredStarbucksValues$pred
regPredStarbucksValues$diffP <- (regPredStarbucksValues$obs - regPredStarbucksValues$pred) / regPredStarbucksValues$obs
mean(abs(BD5TRAIN$Sale_Pri_1))
View(Train666_70cut)
View(Test666_30cut)
# Need to make your dataframes numeric
QuickT_Set <- Quick_train_set #make a copy for safety
colnames(QuickT_Set) #trying to figure out which columns are not numeric
is.numeric(QuickT_Set$Zoning) #f
is.numeric(QuickT_Set$Taxable_La)#f
is.numeric(QuickT_Set$Depth) #f
is.numeric(QuickT_Set$Garage_Spa) #t
is.numeric(QuickT_Set$Total_Liva) #T
is.numeric(QuickT_Set$NEAR_DIST.Vac) #T
is.numeric(QuickT_Set$NEAR_DIST.ComCor) #t
is.numeric(QuickT_Set$NEAR_DIST.SeptaST) #F
is.numeric(QuickT_Set$NEAR_DIST.TrafDat) #T
is.numeric(QuickT_Set$NEAR_DIST.HwyEx) #T
is.numeric(QuickT_Set$Sale_Pri_1) #T
transform(TrainingSet2, NEAR_DIST.SeptaST = as.numeric(NEAR_DIST.SeptaST))
#Remove all $ in these columns "Taxable_Bu" & "Taxable_La"
gsub("$", "", QTrain175$Depth)
head(BD3$Taxable_La)
#what mode
mode(TrainingSet2$NEAR_DIST.SeptaST)
#####
# The droids you are looking for aka. the variables you wanna do regression on
#"Depth" "Garage_Spa" "Total_Liva" "NEAR_DIST.Vac"
#[5] "NEAR_DIST.ComCor" "NEAR_DIST.LIViol" "NEAR_DIST.Retail" "NEAR_DIST.SeptST"
#[9] "NEAR_DIST.TrafDat" "NEAR_DIST.HwyEx" "Sale_Pri_1" "Tax_Build"
#[13] "Tax_Land"
#But one better! - Output this as backup just incase.
write.csv(Quick_Train, file = "C:/Users/Keisan/Documents/CPLN590/Quick_Train.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
write.csv(Quick_Test, file = "C:/Users/Keisan/Documents/CPLN590/Quick_Test.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
stargazer(BD5ols, type="text", title = "Summary Statistics")
View(QTrain70)
str(QTrain70)
head(QTrain70)
#Assign factors as integers
Train85cut$NEAR_DIST.Retail <- as.integer(as.character(Train85cut$NEAR_DIST.Retail))
#Do it for all factoral columns
Train85cut$NEAR_DIST.ComCor <- as.integer(as.character(Train85cut$NEAR_DIST.ComCor))
Train85cut$NEAR_DIST.SeptST <- as.integer(as.character(Train85cut$NEAR_DIST.SeptST))
Train85cut$NEAR_DIST.Vac <- as.integer(as.character(Train85cut$NEAR_DIST.Vac))
Train85cut$NEAR_DIST.LIViol <- as.integer(as.character(Train85cut$NEAR_DIST.LIViol))
Train85cut$NEAR_DIST.TrafDat <- as.integer(as.character(Train85cut$NEAR_DIST.TrafDat))
Train85cut$NEAR_DIST.HwyEx <- as.integer(as.character(Train85cut$NEAR_DIST.HwyEx))
#format summary statistics output
stargazer(OLS_1, type="text", title = "Summary Statistics") #basic
stargazer(OLS_1, type = "text", nobs = FALSE, mean.sd = TRUE, median = TRUE,
+ iqr = TRUE) #more information in charts
stargazer(QTrain70, type = "text", style = "qje") #style difference
stargazer(OLS_1, type = "text",
title = "Summary Statistics",
covariate.labels = c("Garage Space Dimension", "Total Livable Space", "Dist.to Vacancy",
"Nearest Commercial Corridor", "Nearest LI Violation", "Nearest Retail",
"Nearest Septa Stop", "Nearby Traffic Density", "Nearest Highway Exit", "Sale Price", "Building Tax","Land Tax"),
dep.var.caption = "Dependent Variable",
dep.var.labels = "Sale Price") #rename independent labels
stargazer(QTrain70, type = "text",
dep.var.labels.include = FALSE,
model.numbers = FALSE) #not interested in this
##########################################################################
#running a OLS Regression on the dataset
colnames(QTrain70)notepad
########################################## Runs a regression ###############################!!!!!!!!!!!!!!!!!!
OLS_1 <- lm(Sale_Pri_1 ~ Garage_Spa + Total_Liva + NEAR_DIST.Vac + NEAR_DIST.ComCor + NEAR_DIST.LIViol + NEAR_DIST.Retail + NEAR_DIST.SeptST + NEAR_DIST.TrafDat + NEAR_DIST.HwyEx + Tax_Build + Tax_Land, data = Train85cut)
### make dataset smaller
##### tHIS IS LIFE ######################
BD5ols <- lm(Sale_Pri_1 ~ Garage_Spa + Total_Liva + NEAR_DIST_Vac + NEAR_DIST_ComCor + NEAR_DIST_LIViol + NEAR_DIST_Retail + NEAR_DIST_SeptST + NEAR_DIST_TrafDat + NEAR_DIST_HwyEx + Tax_Build + Tax_Land, data = BD5TRAIN)
Rittenhouse_ols <- lm(Sale_Pri_1 ~ Garage_Spa + Total_Liva + NEAR_DIST_Vac + NEAR_DIST_ComCor + NEAR_DIST_LIViol + NEAR_DIST_Retail + NEAR_DIST_SeptST + NEAR_DIST_TrafDat + NEAR_DIST_HwyEx + Tax_Build + Tax_Land, data = Rittenhouse)
cutoff = round(0.5*nrow(Train175cut))
QTrain175 <- QTrain35
Train85cut <- Train175cut[1:cutoff,]
Train <- QTrain[-(1:cutoff),]
dim(Train85cut)
#regression ran after you subsetted the data twice. Hooray! you have some data to plot visualizations
#based on! this is the main point.
#Now just output that file for safety reasons...
write.csv
(OLS_1, file = "C:/Users/Keisan/Documents/CPLN590/OLS_1.csv", append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "") #cant cuz itsaves as a character not a data.frame and cannot be
#coerced into a data.frame
View(OLS_1) #can't view it saves as a function
#summary of OLS_1
summary(BD5ols)
library(corrplot)
CorBD4 <- cor(BD4)
cor(Train85cut) #produces correlation coefficients in list
TR85cut <- cor(Train85cut)
#Now to visualize
corrplot.mixed(TR85cut, order ="AOE",method ="color",addCoef.col="grey") #not working :(
#if column has null values in them
QMat[is.na(Qmat)] <- 0
#pairwise obs
QTMat <- QtestMatrix
cor(QtestMatrix, use="pairwise.complete.obs")
corrplot(TR85cut, method = "number")
#subsetted data with. Now to go through previous steps with reformatting and subsetting
Quick_Train666 <- na.omit(Quick_Train)
Train666 <- Quick_Train666
Train666_70cut <- Train666[1:cutoff,]
is.numeric(Train85cut$NEAR_DIST.LIViol)
#rmse, rse, etc for training set
#now the mean residual or error from the regression 'reg' aka the 'mean absolute error' aka the MAE
mean(abs(Train85cut$Sale_Pri_1))
#calculate the MAPE - or mean absolute percent error aka MAPE
mean(abs(Train85cut$Sale_Pri_1))
#plot variation in regression output
x <- rnorm(1000)
y <- rnorm(1000)
bin<-hexbin(x, y, xbins=50)
plot(bin, main="Hexagonal Binning")
hexbin(Train85cut)
#stylize the corrplot:
col1 <- colorRampPalette(c("#7F0000","red","#FF7F00","yellow","white",
"cyan", "#007FFF", "blue","#00007F"))
col2 <- colorRampPalette(c("#67001F", "#B2182B", "#D6604D", "#F4A582", "#FDDBC7",
"#FFFFFF", "#D1E5F0", "#92C5DE", "#4393C3", "#2166AC", "#053061"))
col3 <- colorRampPalette(c("red", "white", "blue"))
col4 <- colorRampPalette(c("#7F0000","red","#FF7F00","yellow","#7FFF7F",
"cyan", "#007FFF", "blue","#00007F"))
wb <- c("white","black")
view(CorBD4)
corrplot(CorBD4, method="square", order = "FPC", cl.pos="n") #corrplot of Train85cut OLS output, using squares, First Class Principle, no color ramp legend,
head(Train85cut)
#this works for corrplot
corrplot(cor(Train85cut), method="square", order = "FPC", cl.pos="n", p.mat = res1[[1]], sig.level = 0.02, insig = c("p-value"))
pAdj <- p.adjust(c(res1[[1]]), method = "BH")
###select specific columns and drop them
Train85cut2> subset(Train85cut, select=-c(Train85cut,Near_DIST.TrafDat))
R> subset(df, select=-c(z,u))
############## CORRELATION OUTPUT with significance levels indicated by an "X"
cor.mtest <- function(mat, conf.level = 0.95){
mat <- as.matrix(mat)
n <- ncol(mat)
p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n)
diag(p.mat) <- 0
diag(lowCI.mat) <- diag(uppCI.mat) <- 1
for(i in 1:(n-1)){
for(j in (i+1):n){