-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsapiensi.Rmd
1679 lines (1292 loc) · 83.1 KB
/
sapiensi.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: "Analysis of various macroeconomic characteristics"
author:
- Tin Ferković
- Luka Ilić
- Fani Sentinella-Jerbić
- Ana Terović
date: "`r format(Sys.time(), '%d %B %Y')`"
output:
pdf_document:
highlight: tango
number_sections: yes
toc: yes
html_notebook: default
html_document:
toc: yes
df_print: paged
---
```{r, include=FALSE}
require(tidyr)
require(caret)
require(e1071)
require(gridExtra)
require(ggplot2)
require(nortest)
require(fastDummies)
require(nortest)
```
```{r, include=FALSE}
dataset <- read.csv(file='macro_data.csv', sep = ',', stringsAsFactors = FALSE)
num_of_rows <- nrow(dataset)
num_of_col <- ncol(dataset)
```
\newpage
# INTRODUCTION
Macroeconomics examines economy as a whole and is an integral part in governmental decision making on both a national and global scale. Our dataset contains various macroeconomic features, such as GDP per capita and employment rates, for 66 countries.
The main topics covered are examining distributions of various features and whether there are significant outliers, relation between employment rates and GDP, and which variables explain differences in life expectancy. Considering the current global state, we also tried to focus on features which possibly affect climate change and health expenditure (during a pandemic).
Through the analysis we compared Europe to the rest of the world as well as different European regions between each other.
We used descriptive statistics, t-test, ANOVA and also examined linear dependencies through simple and multivariate regression.
Ending consists of a conclusion about everything we have done and comments on the dataset and possible future work.
## Initial mining
```{r, include=FALSE}
#adding a column for colour
#to add colors to your plot add col=colorData$Color at the the end of function call, see examples below
colorData <- read.csv(file='macro_data.csv', sep = ',')
colorData$Color = "black"
colorData$Color[dataset$country == "Croatia"]="red"
colorData$Color
```
Our dataset requires some initial cleaning before doing any analysis. We have detected some dirty data that had to be inspected.
```{r, include=FALSE}
dataset$Net.Official.Development.Assist..received....of.GNI.
```
For example, number of individuals using the Internet per 100 inhabitants:
```{r, echo=FALSE}
dataset$Individuals.using.the.Internet..per.100.inhabitants.
```
```{r, include=FALSE}
dataset$Pop..using.improved.sanitation.facilities..urban.rural....
```
Such features contained too many nonsensical values so we concluded that it makes sense to remove them from the dataset.
It was also necessary to split some of the features whose values were of shape $value/value$ into separate features as well as convert them to proper types.
```{r, include=FALSE}
# remove columns Pop..using.improved.sanitation.facilities..urban.rural.... and Net.Official.Development.Assist..received... from dataset since they hold too many -99 values
# remove column Individuals.using.the.Internet..per.100.inhabitants from the dataset since the interpretation of values is uncertain
drops <- c("Pop..using.improved.sanitation.facilities..urban.rural....","Net.Official.Development.Assist..received....of.GNI.", "Individuals.using.the.Internet..per.100.inhabitants.")
dataset <- dataset[ , !(names(dataset) %in% drops)]
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=Pop..using.improved.drinking.water..urban.rural...., into=c("Pop..using.improved.drinking.water..urban.", "Pop..using.improved.drinking.water..rural."), sep = "/", remove=TRUE, convert=TRUE)
```
```{r, include=FALSE}
dataset$Pop..using.improved.drinking.water..rural.
```
```{r, include=FALSE}
dataset$Pop..using.improved.drinking.water..rural. = as.numeric(dataset$Pop..using.improved.drinking.water..rural.)
```
```{r, include=FALSE}
dataset$Pop..using.improved.drinking.water..rural.
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=Labour.force.participation..female.male.pop...., into=c("Labour.force.participation..male.pop", "Labour.force.participation..female.pop"), sep = "/", remove=TRUE, convert=TRUE)
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=Population.age.distribution..0.14...60..years...., into=c("Population.age.distribution.0-14.years....", "Population.age.distribution.60.years...."), sep = "/", remove=TRUE, convert=TRUE)
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=International.migrant.stock..000...of.total.pop.., into=c("International.mignant.stock.thousands", "International.mignant.stock.percent"), sep = "/", remove=TRUE, convert=TRUE)
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=Education..Primary.gross.enrol..ratio..f.m.per.100.pop.., into=c("Education..Primary.gross.enrol..ratio..f.per.100.pop..", "Education..Primary.gross.enrol..ratio..m.per.100.pop.."), sep = "/", remove=TRUE, convert=TRUE)
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=Education..Tertiary.gross.enrol..ratio..f.m.per.100.pop.., into=c("Education..Tertiary.gross.enrol..ratio..f.per.100.pop..", "Education..Tertiary.gross.enrol..ratio..m.per.100.pop.."), sep = "/", remove=TRUE, convert=TRUE)
```
```{r, include=FALSE}
dataset$Education..Tertiary.gross.enrol..ratio..f.per.100.pop.. = as.numeric(dataset$Education..Tertiary.gross.enrol..ratio..f.per.100.pop..)
dataset$Education..Tertiary.gross.enrol..ratio..m.per.100.pop.. = as.numeric(dataset$Education..Tertiary.gross.enrol..ratio..m.per.100.pop..)
```
```{r, include=FALSE}
dataset <- tidyr::separate(data=dataset, col=Forested.area....of.land.area., into=c("Forested.area", "Forested.percent.of.area"), sep = "/", remove=TRUE, convert=TRUE)
```
```{r}
dataset[dataset == -99] <- NA
```
For the sake of convenience, we also replaced all the cells containing value $-99$ with NA. Basically, in this dataset, $-99$ is a replacement for NA. Lastly, we converted to numeric all the values convertible to numeric. For the ones which can't be converted, we generated NA's.
```{r, include=FALSE}
#šta ovo predstavlja?
dataset$Energy.supply.per.capita..Gigajoules.
```
```{r, include=FALSE}
#OVO PRODISKUTIRATI, ALI TRENUTNO MI TREBA DA BI SE NEKI KASNIJI WARNINGI MAKNULI JER NE MOGU RADIT SA STRINGOM "~0.0"
dataset[dataset == "-~0.0"] <- "-0.05"
dataset[dataset == "~0.0"] <- "0.05"
all_features <- colnames(dataset)
all_features <- all_features[!all_features %in% c("X", "country", "Region", "Energy.supply.per.capita..Gigajoules.")]
for(feature in all_features) {
dataset[[feature]] = as.numeric(dataset[[feature]])
}
dataset$Health..Physicians..per.1000.pop..
```
```{r, include=FALSE}
#Find how many missing values every column has
for (col_name in names(dataset)){
if (sum(is.na(dataset[,col_name])) > 0){
cat('Number of missing values for feature ',col_name, ': ', sum(is.na(dataset[,col_name])),'\n')
}
}
```
```{r, include=FALSE}
mean_quality = fivenum(dataset$Quality.Of.Life.Index)[3]
high_quality_of_life_nations <- dataset[which(dataset$Quality.Of.Life.Index > mean_quality), ]
low_quality_of_life_nations <- dataset[which(dataset$Quality.Of.Life.Index < mean_quality), ]
```
```{r, include=FALSE}
high_quality_of_life_nations_women_parliament_seats = high_quality_of_life_nations$Seats.held.by.women.in.national.parliaments..
low_quality_of_life_nations_women_parliament_seats = low_quality_of_life_nations$Seats.held.by.women.in.national.parliaments..
```
```{r, include=FALSE}
#function which checks for normality
checkForNormalDistribution <- function(data) {
length_of_data = length(data)
#plot the data (histogram)
hist(data, main='Histogram') #breaks might need to be changed depending on the data
#make a q-q plot
#q-q plot is a scatterplot created by plotting two sets of quantiles against each other
#if they come from the same distribution (and in this case we're testing if some data comes from a normal distribution), we should see points forming a roughly straight line
qqnorm(data, pch = 1,col =colorData$Color)
qqline(data, col = "steelblue", lwd = 2, distribution = qnorm)
# do a shapiro-wilk test to get a p-value of a null hypothesis that data is normally distribuited
shapiro.test(data)
#KS test na normalnost
#ks.test(data,'pnorm')
#require(nortest)
#lillie.test(data)
#ks.test(rstandard(selected.model),'pnorm')
}
```
```{r, include=FALSE}
#finding outliers - method 1 - elements outside of interval [Q1 - 1,5IQR, Q3 + 1,5IQR]
findOutliers <- function(data, shouldPrint) {
outliers_values <- boxplot.stats(data)$out
if(length(outliers_values > 0)) {
outliers_rows = which(data %in% c(outliers_values))
if(shouldPrint == TRUE) {
cat("Outlier values: ")
print(outliers_values)
cat("Outlier row numbers: ")
print(outliers_rows)
boxplot(data, main = "Boxplot")
mtext(paste("Outlier values: ", paste(outliers_values, collapse = ", ")))
}
return(outliers_rows)
}
return(NULL)
}
```
```{r, include=FALSE}
#finding outliers - method 2 - elements before and after certain percentile
findOutliers2 <- function(data, shouldPrint) {
lower_bound <- quantile(data, 0.05)
upper_bound <- quantile(data, 0.95)
outliers_rows <- which(data < lower_bound | data > upper_bound)
if(length(outliers_rows) > 0) {
outliers_values <- data[c(outliers_rows)]
if(shouldPrint == TRUE) {
cat("Outlier values: ")
print(outliers_values)
cat("Outlier row numbers: ")
print(outliers_rows)
}
return(outliers_rows)
}
return(NULL)
}
```
```{r, include=FALSE}
rows <- findOutliers(dataset$Population.in.thousands..2017., TRUE)
#print only rows which are population outliers
if(!is.null(rows)) {
print(dataset[rows, ])
}
```
```{r, include=FALSE}
rows <- findOutliers2(dataset$Surface.area..km2., TRUE)
#print only rows which are surface outliers
if(!is.null(rows)) {
print(dataset[rows, ])
}
```
\newpage
```{r, include=FALSE}
dataset.with.dummies.with.qatar = dummy_cols(dataset, select_columns='Region')
continents <- dataset.with.dummies.with.qatar
continents$Colour = "black"
#coloring data based kinda on continents
if(!is.null(continents)) {
#Europe
continents$Colour[continents$Region=="SouthernEurope"] = "green"
continents$Colour[continents$Region=="NorthernEurope"] = "green"
continents$Colour[continents$Region=="WesternEurope"] = "green"
continents$Colour[continents$Region=="EasternEurope"] = "green"
#Africa
continents$Colour[continents$Region=="SouthernAfrica"] = "yellow"
continents$Colour[continents$Region=="NorthernAfrica"] = "yellow"
#Asia
continents$Colour[continents$Region=="SouthernAsia"] = "red"
continents$Colour[continents$Region=="NorthernAsia"] = "red"
continents$Colour[continents$Region=="WesternAsia"] = "red"
continents$Colour[continents$Region=="EasternAsia"] = "red"
continents$Colour[continents$Region=="South-easternAsia"] = "red"
#Americas
continents$Colour[continents$Region=="SouthAmerica"] = "blue"
continents$Colour[continents$Region=="NorthernAmerica"] = "blue"
continents$Colour[continents$Region=="CentralAmerica"] = "blue"
#Oceania
continents$Colour[continents$Region=="Oceania"] = "purple"
}
```
```{r, include=FALSE}
#Europe colours
europe<- continents[continents$Region=="WesternEurope", ]
b <- continents[continents$Region=="EasternEurope",]
c <- continents[continents$Region=="NorthernEurope",]
d <- continents[continents$Region=="SouthernEurope",]
europe<- merge(europe,b, all = TRUE)
europe <- merge(europe,c, all = TRUE)
europe <- merge(europe,d, all = TRUE)
```
```{r, include=FALSE}
#playing with women in parlament
rest_of_the_world = continents[!continents$country %in% europe$country, ]
hist(rest_of_the_world$Seats.held.by.women.in.national.parliaments..)
plot(rest_of_the_world$Seats.held.by.women.in.national.parliaments.., col=rest_of_the_world$Colour)
boxplot(rest_of_the_world$Seats.held.by.women.in.national.parliaments..)
hist(europe$Seats.held.by.women.in.national.parliaments..)
plot(europe$Seats.held.by.women.in.national.parliaments..,col=europe$Colour)
boxplot(europe$Seats.held.by.women.in.national.parliaments..)
summary(rest_of_the_world$Seats.held.by.women.in.national.parliaments..)
summary(europe$Seats.held.by.women.in.national.parliaments..)
```
```{r, include=FALSE}
#Europe fun
plot(europe$GDP.per.capita..current.US..,col=europe$Colour)
plot(europe$Employment..Agriculture....of.employed.,col=europe$Colour)
plot(europe$Infant.mortality.rate..per.1000.live.births,col=europe$Colour)
plot(europe$Health..Physicians..per.1000.pop..,col=europe$Colour)
plot(europe$Education..Government.expenditure....of.GDP.,col=europe$Colour)
```
```{r, include=FALSE}
rest_of_the_world = dataset[!dataset$country %in% europe$country, ]
rest_of_the_world
```
## Descriptive statistics
Descriptive statistics, in short, help describe and understand the features of a specific dataset by giving short summaries about the sample and measures of the data. As a good intro to more complex topics, we are here presenting a general overview of our dataset.
```{r, echo=FALSE}
cat(' Number of rows and columns, respectively: ', num_of_rows, num_of_col)
```
One can see that our dataset is quite peculiar, having more columns than rows. We will keep this in mind through further analysis.
We want to see which parts of the world are represented in our dataset. Here we are using a polar graph for visualization.
```{r, echo=FALSE}
bar <- ggplot(data = dataset) +
geom_bar(
mapping = aes(x = Region, fill = Region),
show.legend = FALSE,
width = 1,
) +
theme(aspect.ratio = 1)
bar + coord_polar() +
labs(x = NULL , y = NULL) +
ggtitle("Number of countries by area")
```
\newpage
### Distributions
Wanting to examine the distributions across all countries, we shall plot multiple histograms with mean as a measure of central tendency as well as the density to get inspiration for further analysis.
One of the most common indicators of a country's well being is its GDP, so we plot the histogram of GDP _per capita_ as it generally delivers more of a prosperity measure than the total GDP. We are expecting to see a smaller number of countries with a large GDP _per capita_ and a larger amount of countries with small or average GDP.
```{r, echo=FALSE}
gdp_histo <- ggplot(dataset, aes(x=GDP.per.capita..current.US..)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="pink") +
geom_vline(aes(xintercept=mean(GDP.per.capita..current.US..)),
color="black", linetype="dashed", size=1) +
ggtitle("GDP per capita") + xlab("GDP per capita in US $") + ylab("Density")
gdp_histo_trans <- ggplot(dataset, aes(x=GDP.per.capita..current.US..)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="pink") +
geom_vline(aes(xintercept=mean(GDP.per.capita..current.US..)),
color="black", linetype="dashed", size=1) + scale_x_log10() +
ggtitle("GDP per capita transformed") + xlab("GDP per capita in US $") + ylab("Density")
grid.arrange(gdp_histo,
gdp_histo_trans,
ncol = 2)
```
As we have assumed, there are more countries with lower GDP _per capita_ than those with a high GDP _per capita_. Considering we have an asymmetrical distribution, we decided to plot the mean as an expression of central tendency as seen on the graph in the shape of a dashed line. However, in order to run any significant tests one should check for normal distribution so we decided to also plot the log transformed histogram. Unfortunately, the distribution was not normal even after transformation.
\newpage
Furthermore, we have plotted various other features in order to get a grip of the way our data behaves and gain some intuition.
```{r, echo=FALSE}
density_purchasing_power <- ggplot(dataset, aes(x=Purchasing.Power.Index)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Purchasing.Power.Index)),
color="black", linetype="dashed", size=1) +
ggtitle("Purchasing power") + xlab("Purchasing power index") + ylab("Density")
density_health <- ggplot(dataset, aes(x=Health.Care.Index)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Health.Care.Index)),
color="black", linetype="dashed", size=1) +
ggtitle("Health care") + xlab("Health care index") + ylab("Density")
density_pollution <- ggplot(dataset, aes(x=Pollution.index)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue")+
geom_vline(aes(xintercept=mean(Pollution.index)),
color="black", linetype="dashed", size=1) +
ggtitle("Pollution") + xlab("Pollution index") + ylab("Density")
density_safety <- ggplot(dataset, aes(x=Safety.Index)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue")+
geom_vline(aes(xintercept=mean(Safety.Index)),
color="black", linetype="dashed", size=1) +
ggtitle("Safety") + xlab("Safety index") + ylab("Density")
density_mobile <- ggplot(dataset, aes(x=Mobile.cellular.subscriptions..per.100.inhabitants..1)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Mobile.cellular.subscriptions..per.100.inhabitants..1)),
color="black", linetype="dashed", size=1) +
ggtitle("Mobile subscriptions") + xlab("Subs per 100 inhabitants") + ylab("Density")
density_urban <- ggplot(dataset, aes(x=Urban.population....of.total.population._x)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Urban.population....of.total.population._x)),
color="black", linetype="dashed", size=1) +
ggtitle("Urban population %") + xlab("Urban population % of total") + ylab("Density")
density_life_exp <- ggplot(dataset, aes(x=Life.expectancy.at.birth..total..years.)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Life.expectancy.at.birth..total..years.)),
color="black", linetype="dashed", size=1) +
ggtitle("Life expectancy") + xlab("Life expectancy") + ylab("Density")
density_living <- ggplot(dataset, aes(x=Cost.Of.Living.Index)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Cost.Of.Living.Index)),
color="black", linetype="dashed", size=1) +
ggtitle("Cost of living index") + xlab("Cost of living index") + ylab("Density")
density_quality <- ggplot(dataset, aes(x=Quality.Of.Life.Index)) +
geom_histogram(aes(y=..density..), color="black", fill="white", bins=8) +
geom_density(alpha=.2, fill="lightblue") +
geom_vline(aes(xintercept=mean(Quality.Of.Life.Index)),
color="black", linetype="dashed", size=1) +
ggtitle("Quality of life") + xlab("Quality of life index") + ylab("Density")
grid.arrange(density_safety,
density_health,
density_pollution,
density_purchasing_power,
density_living,
density_quality,
density_mobile,
density_urban,
density_life_exp,
ncol = 3)
```
As it can be seen from the graphs, most of the features are not normally distributed. That, along with the fact that there are only 66 countries, makes some statistical hypotheses and conclusions more difficult - or as we see it, more challenging.
```{r, echo=FALSE}
#FUNCTION FOR REGULAR R GRAPHING
#graph_histogram <- function(x){
# par(mfrow=c(1,2))
# hist(x, main='Pre log',xlab='Value',ylab='Frequency', col="lightsteelblue", border="white")
# abline(v=mean(x),col="darkgrey", lty = 2)
# hist(log(x), main='Post log',xlab='Value',ylab='Frequency', col="lightsteelblue", border="white")
# abline(v=mean(log(x)),col="darkgrey", lty = 2)
#}
#example of using this function
#graph_histogram(dataset$International.trade..Exports..million.US..)
```
\newpage
Since we also want to focus on the factors which are somewhat correlated to the GDP throughout our further analysis, we want to check out some candidate variables and their properties.
Here we can see the box plot showing contribution to GVA and employment percentage by each sector of economy.
```{r, echo=FALSE}
dataset$Economy..Agriculture....of.GVA. = as.numeric(dataset$Economy..Agriculture....of.GVA.)
box_sectors_by_GVA_contribution <- ggplot(stack(dataset[c(11:13)]), aes(x = ind, y = values, fill=ind)) + geom_boxplot() +
ggtitle("Percentage of GVA") + xlab("Economic sector") + ylab("Percentage of GVA") +
theme(legend.position="none") + scale_x_discrete(guide = guide_axis(n.dodge=3))
box_sectors_by_employment <- ggplot(stack(dataset[c(14:16)]), aes(x = ind, y = values, fill=ind)) + geom_boxplot() +
ggtitle("Percentage of empolyment") + xlab("Economic sector") + ylab("Percentage of employment") +
theme(legend.position="none") + scale_x_discrete(guide = guide_axis(n.dodge=3))
grid.arrange(box_sectors_by_GVA_contribution, box_sectors_by_employment, ncol = 2)
```
A few interesting notes can be taken from this. Although the agriculture contribution to the GVA is quite small, there seem to be more more people working in the sector than one might expect. Industry seems to have a bigger influence on the GVA considering how many people are working in the field. This can naturally be attributed to the fact that there are factory machines doing the work. We can also see that the employment in the services sector varies the most out of the three sectors.
\newpage
### Significant outliers
Interesting part of the initial exploration is finding outlier values.
For example, the US is an outlier in all air transport, far surpassing the competition as seen on the following graph:
```{r, echo=FALSE}
#cat("Freight million ton-km \n")
#summary(dataset.with.dummies.with.qatar$Air.transport..freight..million.ton.km.)
#cat("\nPassengers carried")
#summary(dataset.with.dummies.with.qatar$Air.transport..passengers.carried)
par(mfrow=c(1,2))
plot(dataset$X,
dataset$Air.transport..freight..million.ton.km.,
col= continents$Colour,
xlab="Countries", ylab="Air transport, freight")
plot(dataset$X,
dataset$Air.transport..passengers.carried,
col= continents$Colour,
xlab="Countries", ylab="Air transport, passengers carried")
```
Qatar is also an outlier worth of mentioning, but it will be later discussed throughout the paper.
\newpage
We took the next step and automatized the process of finding the outliers in order to see which countries have the most outliers across all parameters.
```{r, include=FALSE}
#check if a nation (row number) is an outlier in a provided feature
checkNationOutlierInFeature <- function(nation_row_number, feature) {
outliers = findOutliers(dataset[[feature]], FALSE)
if(is.null(outliers) || !(nation_row_number %in% c(outliers))) {
return(FALSE)
}
return(TRUE)
}
```
```{r, include=FALSE}
checkNationOutlierInFeature(9, "Surface.area..km2.")
```
```{r, include=FALSE}
#find in which features a certain nation is an outlier (don't look at features such as country, region etc.)
findAllOutlierFeaturesOfANation <- function(row_number) {
all_features <- colnames(dataset)
all_features <- all_features[!all_features %in% c("X", "country", "Region", "Energy.supply.per.capita..Gigajoules.")]
outlier_features = NULL
for(feature in all_features) {
if(checkNationOutlierInFeature(row_number, feature) == TRUE) {
if(is.null(outlier_features)) {
outlier_features <- c(as.character(feature))
} else {
outlier_features <- append(outlier_features, as.character(feature))
}
}
}
if(length(outlier_features) == 0) {
cat(as.character(dataset[row_number, "country"]), " isn't outlier in any features.\n")
} else {
cat(as.character(dataset[row_number, "country"]), " is outlier in features: ")
for (i in 1:length(outlier_features)) {
cat(outlier_features[i])
if (i != length(outlier_features)) {
cat(", ")
} else {
cat("\n")
}
}
}
return(length(outlier_features))
}
```
```{r, echo=FALSE, results=FALSE}
num_of_outlier_features <- vector(mode="integer")
for (i in 1:length(row.names(dataset))) {
num_of_outlier_features[i] <- findAllOutlierFeaturesOfANation(i)
cat("\n")
}
dataset$Number.of.Outlier.Features <- num_of_outlier_features
```
```{r, echo=FALSE}
ggplot(dataset, aes(reorder(country,
Number.of.Outlier.Features),
Number.of.Outlier.Features)) +
geom_col() +
labs(title="Number of outlier features by countries", x="Country", y="Number of outlier features") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
```
We can see that the USA has outlier values in most categories out of given countries. One can also notice that Croatia does not have outlier values in any of the given features. Despite that, in the rest of the document it will be colored red in order to see how it is ranks in comparison to other countries.
\newpage
# TESTING HYPOTHESIS
In this section we will test different assumptions using the t-test.\newline
In our t.test function we check the distribution of the data by drawing graphs and we also check whether the variances are equal to be able to conduct the internal R supplied t.test. When making a decision we look at the p-value. If the p-value of the t-test is smaller than confidence interval we can reject the null hypothesis in favor of the alternative hypothesis and if the p-value is bigger we cannot reject null hypothesis.\newline
Lets analyze Europe compared to other world countries while focusing on current world issues.
```{r, include=FALSE}
#tryout
#population growth
plot(dataset.with.dummies.with.qatar$X, dataset.with.dummies.with.qatar$Population.growth.rate..average.annual..., col = continents$Colour,)
boxplot(rest_of_the_world$Population.growth.rate..average.annual...,europe$Population.growth.rate..average.annual...,names=c("Rest of the world population growth", "Europe population growth"), main="Distribution of population growth")
#-provjera normalnosti
hist(rest_of_the_world$Population.growth.rate..average.annual...)
hist(europe$Population.growth.rate..average.annual...)
qqnorm(rest_of_the_world$Population.growth.rate..average.annual...)
qqline(rest_of_the_world$Population.growth.rate..average.annual..., lwd =2)
qqnorm(europe$Population.growth.rate..average.annual...)
qqline(europe$Population.growth.rate..average.annual..., lwd=2)
#--normalno su distribuirane (diskutiraj rest of the world)
summary(rest_of_the_world$Population.growth.rate..average.annual...)
summary(europe$Population.growth.rate..average.annual...)
#-provjera varijanci
var(rest_of_the_world$Population.growth.rate..average.annual...)
var(europe$Population.growth.rate..average.annual...)
#--varijance nisu jednake
#-t test
t.test(rest_of_the_world$Population.growth.rate..average.annual...,europe$Population.growth.rate..average.annual..., alt = "greater", var.equal = FALSE)
#--p vrijednost jako mala -> odbacujemo null hipotezu te prihvcamo nasu pretpostavku
```
```{r, include=FALSE}
#dataset[!dataset$country %in% europe$country, ]
myTtest <- function(data1, data2, talt, tpaired){
outliers1<- findOutliers(data1, FALSE)
outliers2<- findOutliers(data2, FALSE)
newEuropeColours <- europe
if (!is.null(outliers1)) {
data1 <- data1[-c(outliers1)]
}
if (!is.null(outliers2)){
data2 <- data2[-c(outliers2)]
newEuropeColours <- europe[-c(outliers2),]
}
par(mfrow=c(2,4))
#-provjera normalnosti
hist(data1, main="Rest of the world", xlab="Rest of the world")
qqnorm(data1, main="Rest of the world")
qqline(data1, lwd =2)
hist(data2, main="Europe", xlab="Europe")
qqnorm(data2, col=newEuropeColours$Colour, main="Europe")
qqline(data2, lwd=2)
boxplot(data1,data2,names=c("Rest of the world", "Europe"), main="Distribution",cex.axis=0.7 )
#-provjera varijanci
vrijednost <- var(data1)/var(data2)
if (!is.na(vrijednost) & vrijednost == 1) {
vrijednost <- TRUE
}
else{
vrijednost <- FALSE
}
#-t test
t.test(data2,data1, alt = talt, var.equal = vrijednost, paired = tpaired)
}
```
## Climate change
```{r, include=FALSE}
#climate
myTtest(rest_of_the_world$Climate.index,europe$Climate.index, "greater", FALSE)
#I DONT KNOW
#p vrijednost jako mala -> odbacujemo null hipotezu te prihvcamo nasu pretpostavku
#1. rest of the world not quite normaly distributed
#2. p value not that small
```
### Assumption: Pollution in Europe is lower than in the rest of the world.
```{r}
myTtest(rest_of_the_world$Pollution.index,europe$Pollution.index, "less", FALSE)
```
Based on the p-value we can reject the null hypothesis in favor of the alternative hypothesis meaning that the pollution in Europe is lower than that in the rest of the world.
```{r, include=FALSE}
myTtest(rest_of_the_world$Quality.Of.Life.Index,europe$Quality.Of.Life.Index, "greater", FALSE)
```
### Assumption: Population growth in Europe is lower than in other countries.
```{r}
myTtest(rest_of_the_world$Population.growth.rate..average.annual...,europe$Population.growth.rate..average.annual...,"less", FALSE)
```
Based on the p-value we can reject the null hypothesis in favor of the alternative hypothesis meaning that the population growth in Europe is slower than that in the rest of the world.
\newpage
### Assumption: Based on the fact that the pollution in Europe is lower than in the rest of the world we are making an asumption that the amount of people working in Agriculture sector is much higher than in the Industry sector.
```{r, include=FALSE}
data1 <-europe$Employment..Industry....of.employed.
data2<-europe$Employment..Agriculture....of.employed.
outliers1<- findOutliers(data1, FALSE)
outliers2<- findOutliers(data2, FALSE)
newEuropeColours <- europe
if (!is.null(outliers1)) {
data1 <- data1[-c(outliers1)]
}
if (!is.null(outliers2)){
data2 <- data2[-c(outliers2)]
newEuropeColours <- europe[-c(outliers2),]
}
#normality check
```
```{r, echo=FALSE}
par(mfrow=c(2,4))
hist(data1, main="Industry sector", xlab="Industry sector")
qqnorm(data1, main="Industry sector")
qqline(data1, lwd =2)
hist(data2, main="Agriculture sector", xlab="Agriculture sector")
qqnorm(data2, col=newEuropeColours$Colour, main="Agriculture sector")
qqline(data2, lwd=2)
boxplot(data1,data2,names=c("Industry sector", "Agriculture sector"), main="Distribution")
t.test(europe$Employment..Agriculture....of.employed.,europe$Employment..Industry....of.employed., alt = "less", var.equal = FALSE, paired = TRUE, conf.level = 0.9)
```
Based on the p-value we can reject the null hypothesis meaning that the amount of people working in Industry sector in Europe is higher than in Agriculture.
\newpage
## Corona virus
### Assumption: Health expenses in Europe are greater than in the rest of the world.
```{r}
myTtest(log(rest_of_the_world$Health..Total.expenditure....of.GDP.),log(europe$Health..Total.expenditure....of.GDP.),"greater", FALSE)
```
Based on the p-value we can reject the null hypothesis meaning that health expanses in Europe are higher than that in the rest of the world.
\newpage
### Assumption: There are more older people in Europe than in the rest of the world.
```{r}
myTtest(log(rest_of_the_world$Population.age.distribution.60.years....),log(europe$Population.age.distribution.60.years....),"greater", FALSE)
```
Based on the p-value we can reject the null hypothesis in favor of the alternative hypothesis meaning that there are more older people in Europe than in the rest of the world.
\newpage
## Gender equality
### Assumption: There are more women in parliament in Europe than in the rest of the world.
```{r}
myTtest(sqrt(rest_of_the_world$Seats.held.by.women.in.national.parliaments..),sqrt(europe$Seats.held.by.women.in.national.parliaments..),"greater", FALSE)
```
Based on the p-value we can reject the null hypothesis in favor of the alternative hypothesis meaning that there are more women in parliaments in Europe than in the rest of the world.
\newpage
### Assumption: There are more women going to college in Europe than in the rest of the world.
```{r}
myTtest(rest_of_the_world$Education..Tertiary.gross.enrol..ratio..f.per.100.pop..,europe$Education..Tertiary.gross.enrol..ratio..f.per.100.pop..,"greater", FALSE)
```
Based on the p-value we can reject the null hypothesis in favor of the alternative hypothesis meaning that there are more women in parliaments in Europe than in the rest of the world.
\newpage
### Assumption: There is no difference in the number of girls compared to the number of boys going to school.
```{r, include=FALSE}
data1 <-europe$Education..Primary.gross.enrol..ratio..m.per.100.pop..
data2<-europe$Education..Primary.gross.enrol..ratio..f.per.100.pop..
outliers1<- findOutliers(data1, FALSE)
outliers2<- findOutliers(data2, FALSE)
newEuropeColours <- europe
if (!is.null(outliers1)) {
data1 <- data1[-c(outliers1)]
}
if (!is.null(outliers2)){
data2 <- data2[-c(outliers2)]
newEuropeColours <- europe[-c(outliers2),]
}
#normality check
```
```{r, echo=FALSE}
par(mfrow=c(2,4))
hist(data1, main="Boys in school", xlab="Boys in school")
qqnorm(data1, main="Boys in school")
qqline(data1, lwd =2)
hist(data2, main="Girls in school", xlab="Girls in school")
qqnorm(data2, col=newEuropeColours$Colour, main="Girls in school")
qqline(data2, lwd=2)
boxplot(data2,data1,names=c("Boys in school in Europe", "Girls in school in Europe"), main="Distribution")
t.test(data1,data2, alt = "greater", var.equal = FALSE, paired = TRUE )
```
Based on the p-value we cannot reject the null hypothesis in favor of the alternative hypothesis meaning that there is no difference of boys and girls going to school in Europe.
```{r, include=FALSE}
myAnovaLogTest <- function(data, labelX){
#provjera normalnosti
print("Testing normality:")
#print(lillie.test(log(data)))
print(lillie.test(log(data[europe$Region=="WesternEurope"])))
print(lillie.test(log(data[europe$Region=="EasternEurope"])))
print(lillie.test(log(data[europe$Region=="NorthernEurope"])))
print(lillie.test(log(data[europe$Region=="SouthernEurope"])))
par(mfrow=c(2,2))
# hist(log(europe$GDP.per.capita..current.US..), main = "Europe - GDP per capita")
hist(log(data[europe$Region=="WesternEurope"]), main = "Western Europe", xlab=labelX)
hist(log(data[europe$Region=="EasternEurope"]), main = "Eastern Europe", xlab=labelX)
hist(log(data[europe$Region=="NorthernEurope"]), main = "Northern Europe", xlab=labelX)
hist(log(data[europe$Region=="SouthernEurope"]), main = "Southern Europe", xlab=labelX)
print("Testing variance homogeneity:")
temp1 <- bartlett.test(log(data) ~ europe$Region)
print(temp1)
print(var(log(data[europe$Region=="WesternEurope"])))
print(var(log(data[europe$Region=="EasternEurope"])))
print(var(log(data[europe$Region=="NorthernEurope"])))
print(var(log(data[europe$Region=="SouthernEurope"])))
par(mfrow=c(1,1))
boxplot(log(data) ~ europe$Region, xlab = "European regions", ylab = labelX, cex.axis=0.75)
message("ANOVA:")
a= aov((log(data) ~ europe$Region))
summary(a)
}
myAnovaTest <- function(data, labelX){
#provjera normalnosti
print("Testing normality:")
#print(lillie.test(log(data)))
print(lillie.test((data[europe$Region=="WesternEurope"])))
print(lillie.test((data[europe$Region=="EasternEurope"])))
print(lillie.test((data[europe$Region=="NorthernEurope"])))
print(lillie.test((data[europe$Region=="SouthernEurope"])))
par(mfrow=c(2,2))
# hist(log(europe$GDP.per.capita..current.US..), main = "Europe - GDP per capita")
hist((data[europe$Region=="WesternEurope"]), main = "Western Europe", xlab=labelX)
hist((data[europe$Region=="EasternEurope"]), main = "Eastern Europe", xlab=labelX)
hist((data[europe$Region=="NorthernEurope"]), main = "Northern Europe", xlab=labelX)
hist((data[europe$Region=="SouthernEurope"]), main = "Southern Europe", xlab=labelX)
print("Testing variance homogeneity:")
temp1 <- bartlett.test((data) ~ europe$Region)
print(temp1)
print(var((data[europe$Region=="WesternEurope"])))
print(var((data[europe$Region=="EasternEurope"])))
print(var((data[europe$Region=="NorthernEurope"])))
print(var((data[europe$Region=="SouthernEurope"])))
par(mfrow=c(1,1))
boxplot((data) ~ europe$Region, xlab = "European regions", ylab = labelX, cex.axis=0.75)
message("ANOVA:")
a= aov(((data) ~ europe$Region))
summary(a)
}
```
\newpage
# ANOVA
After comparing Europe to the rest of the world we decided to test similar assumptions between European regions.
## Quick introduction
ANOVA is a method for analysing differences between group means in a sample. We presume that the total variance is caused by variability inside each group(result of coincidence) as well as variability between the groups. The latter being the result of differences between group means. Our goal is to determine whether those differences between groups are statistically significant.
For ANOVA to work the following assumptions must be met:
* independence between data in samples
* normal distribution of data
* variance homogeneity between samples
Our goal is to use ANOVA to test whether all European regions have the same GDP per capita mean.
First we correct the Region from character to factor and continue to test assumptions above.
Independence is implied because these are all separate countries.
```{r}
europe$Region <- as.factor(europe$Region)
```
## Testing mean assumptions
### Assumption: GDP per capita mean is the same across all European regions
```{r}
myAnovaLogTest(europe$GDP.per.capita..current.US..,"log(GDP per capita)")
```
All tests, except normality for Western and Northern Europe, are favourable.
Our groups are of similar size and knowing that ANOVA is robust with respect to normality for similarly sized groups we proceeded.
ANOVA showed that the means of GDP per capita for regions are not the same. The same can be seen from the boxplot.
### Assumption: Industry makes up the same amount of economy across all European regions
```{r}
myAnovaTest(europe$Economy..Industry....of.GVA., "Industry in economy")
```
All tests are favourable for ANOVA assumptions and we can proceed
From the box plot, other than Eastern Europe, all regions appear to have similar means and with ANOVA using 1% significance we cannot reject the assumption that all groups have the same means.
### Assumption: Mean of Urban population in total population is the same across all European regions
```{r}
myAnovaTest(europe$Urban.population....of.total.population._x, "Urban population in total pop.")
```
Tests are favourable, the only one raising suspicion is Lilliefors normality test Eastern European region.
Our groups are of similar size and knowing that ANOVA is robust with respect to normality for similarly sized groups we proceeded.
\newline
From both the box plot and ANOVA we can see rejection of the assumption that all regions have the same part of urban population in total population.
### Assumption: Mean of Quality of life index is the same across all European regions
```{r}
myAnovaTest(europe$Quality.Of.Life.Index, "Quality of life index")
```
Tests are favourable, the only one raising suspicion is Lilliefors normality test Northern European region.
Our groups are of similar size and knowing that ANOVA is robust with respect to normality for similarly sized groups we proceeded.
\newline
From both the box plot and ANOVA we can see rejection of the assumption that all regions have the same Quality of life index mean.
### Assumption: Health expenditure mean is the same across all European regions
```{r}
myAnovaTest(europe$Health..Total.expenditure....of.GDP., "Total health expenditure")
```
Normality tests are favourable, but the variances do not seem to be homogeneous.
Our groups are of similar size and knowing that ANOVA is robust with respect to variance homogeneity for similarly sized groups we proceeded.
\newline
From both the box plot and ANOVA we can see rejection of the assumption that all regions have the same Health expenditure mean.
\newpage
# LINEAR REGRESSION
Linear regression is a method of modelling the relationship between a scalar response and one or more variables (regressors).
It is mostly used for predicting a value of a variable by using values of some different variable(s).
Training is done on a train dataset and testing (predicting) on a never before seen data.
## Predicting GDP per capita with employments per sectors
Let's first visualize the data we're working with.
```{r, include=FALSE}
without_qatar = dataset[-c(44),]
```
```{r, include=FALSE}
employment_agriculture = dataset$Employment..Agriculture....of.employed.
employment_services = dataset$Employment..Services....of.employed.
employment_industry = dataset$Employment..Industry....of.employed.
gdp_per_capita = dataset$GDP.per.capita..current.US..
employment_agriculture_without_qatar = without_qatar$Employment..Agriculture....of.employed.
employment_services_without_qatar = without_qatar$Employment..Services....of.employed.
employment_industry_without_qatar = without_qatar$Employment..Industry....of.employed.
gdp_per_capita_without_qatar = without_qatar$GDP.per.capita..current.US..
```
```{r, include=FALSE}