#Being interested in politics, we also decided to focus on studying how age can influence the party for which respondents vote and whether there is a correlation. Our assumptions stop at the fact that older people prefer to vote for the party of conservatives.

#Survey question: “Is it true that English people who take part in the choice of parties have the same age category?”.

Step 1.

data <- read.spss('C:/Users/Asus/OneDrive/Рабочий стол/R - history/Project.sav', to.data.frame = TRUE)
## Warning in read.spss("C:/Users/Asus/OneDrive/Рабочий стол/R -
## history/Project.sav", : Undeclared level(s) 0, 1, 2, 5, 10, 15, 20, 30, 33, 40,
## 45, 50, 60, 65, 70, 75, 90, 105, 120, 125, 135, 140, 150, 180, 210, 230, 240,
## 245, 270, 300, 330, 360, 420, 480, 540, 600, 605, 610, 660, 780, 900, 1047,
## 1200 added in variable: nwspol
## Warning in read.spss("C:/Users/Asus/OneDrive/Рабочий стол/R -
## history/Project.sav", : Undeclared level(s) 0, 5, 10, 15, 20, 30, 35, 45, 60,
## 64, 65, 80, 85, 90, 120, 123, 125, 150, 165, 180, 185, 204, 210, 240, 245, 270,
## 300, 330, 360, 365, 390, 420, 425, 450, 480, 510, 540, 600, 660, 720, 750, 780,
## 840, 900, 960, 1080, 1140, 1200 added in variable: netustm
## Warning in read.spss("C:/Users/Asus/OneDrive/Рабочий стол/R -
## history/Project.sav", : Undeclared level(s) 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 added in variable: agea
ESS = data %>%
  select(name, nwspol, polintr, vote, happy, prtvtdgb, netustm, pbldmna, edubgb2, pstplonl, agea)

ESS$agea <- as.numeric(ESS$agea)

ESS <- ESS %>%  
  filter(prtvtdgb %in% c("Conservative", "Labour", "Liberal Democrat"))


###Before checking the normality assumption, we first need to visualize our data.

ggplot(ESS) + 
  geom_boxplot(aes(prtvtdgb, agea), col = c("#3F72AF", "#A8D8EA", "#71C9CE")) + 
  theme_pander() + 
  labs(
    x = " \n Party voted for at last election ",
    y = "Age of respondent \n",
    title = "Relationship between gender and party voted for at last election") +
  theme(plot.title = element_text(face = "bold", size = 10, hjust = 0.5), 
        text = element_text(size = 6), legend.title = element_blank())
## Warning: Removed 3 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

### according to our data, the values of the variables "Conservative" and "Liberal Democrat" are approximately the same, although there is a shift of the median in the variable "Liberal Democrat" slightly lower. At the same time, the values of the variable "Labor" differ significantly from the other two variables, because, first, the minimum and maximum values are lower than the other variables, but the median value is not significantly different from the median value of the variable "Liberal Democrat".

Step 2.

#Compiling a linear regression we check for independence between the residuals of the data.  
model <- lm(agea ~ prtvtdgb, data=ESS)
durbinWatsonTest(model)
##  lag Autocorrelation D-W Statistic p-value
##    1      0.04459946      1.907975    0.23
##  Alternative hypothesis: rho != 0
# Since the p-value > 0.05, we accept the hypothesis that the residuals of these variables have no correlation.

shapiro.test(ESS$agea)
## 
##  Shapiro-Wilk normality test
## 
## data:  ESS$agea
## W = 0.97245, p-value = 1.786e-10
# By applying this test we consider the possibility of normal distribution of the data. Having obtained the results of p-value we can conclude that we reject the null hypothesis of normal distribution.

leveneTest(ESS$agea~ESS$prtvtdgb)
## Levene's Test for Homogeneity of Variance (center = median)
##        Df F value  Pr(>F)  
## group   2  2.7696 0.06335 .
##       725                  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#The obtained test values indicate that the variance values of the selected values are the same - homogenous, i.e. the null statistical hypothesis of variance equality is accepted
dotplot(agea ~ prtvtdgb,
  data = ESS)

#The points of this graph indicate approximate equality of variance, as they have approximately the same distribution range



####Hypotheses for the ANOVA test
#H0: μ(Labour)= μ(Conservative) = μ(Liberal Democratic) ⇒ the 3 parties are equal in terms of votion
#H1: at least one mean is different ⇒ at least one party is different from the other 2 parties in terms of votion
one.way.anova <- oneway.test(ESS$agea~ESS$prtvtdgb, var.equal = T)
# Based on the obtained results we can conclude that, since the value of F = 38.167 and p-value < 2.2e-16, which is less than 0.05, we get that the null hypothesis should be rejected. This means that at least 1 type of party is different from the others in terms of age of respondents and is statistical significant.

#Based on these findings we can apply the anova test
aov.output <- aov(ESS$agea~ESS$prtvtdgb)

#we check the normality of the data by the graphs, which show a slight shift of the data to the right side (density graph). Also looking at the qqPlot result we can observe the values of outliers in the right side, and since the residuals do not fall into the confidence interval, we can say that the residuals do not correspond to the normal distribution
par(mfrow = c(1, 2))
plot(density(residuals(aov.output)))[11:12]
## NULL
qqPlot(aov.output$residuals,
  id = FALSE)

describe(residuals((aov.output)))[11:12]
##     skew kurtosis
## X1 -0.23    -0.69
#A negative skew value proves negative left-to-left asymmetry of the data, i.e. the tail of the values is closer to negative values, and a negative kurtosis value indicates that the data can produce fewer extreme outliers than a normal distribution. 

# Also to check the normality of residuals
layout(matrix(1:4, 2, 2))
plot(aov.output)

#By looking at the top two graphs we can say that the line that means that the residuals are randomly distributed and have constant variance, although there is a small shift at a point around the value 48. Paying attention to the upper right graph we can also observe that the line goes downhill, but it is approximately straight, so we can say that the groups have approximately the same variance value. The data on the qqplot graph follows the line roughly, but with a slight slope in the upper corner, which means that there is a normal distribution of residuals




#To be sure of the results, we check the statement about normality of residuals.
shapiro.test(aov.output$residuals)
## 
##  Shapiro-Wilk normality test
## 
## data:  aov.output$residuals
## W = 0.98453, p-value = 5.835e-07
#Given the results of the test we see that the p-value is very small and smaller than the 95% confidence interval, as a result we can finally be sure that the residuals do not have a normal distribution as we reject the null hypothesis of normality.

Step 3.

#Since the p-value indicates that differences between some groups have been observed, we need to find out between which groups there is this difference.
kruskal.test(x = ESS$agea, g = ESS$prtvtdgb)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  ESS$agea and ESS$prtvtdgb
## Kruskal-Wallis chi-squared = 66.384, df = 2, p-value = 3.844e-15
#After finding that there are differences, Since the variance values are equal to each other, we apply Tukey Honestly Significance test which will compare all the groups of values.

Tukey <- TukeyHSD(aov.output, conf.level= .95)

par(mar = c(3, 13, 3, 3))
plot(Tukey, las = 2, col = "green")

TukeyHSD(aov.output, conf.level= .95)
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = ESS$agea ~ ESS$prtvtdgb)
## 
## $`ESS$prtvtdgb`
##                                     diff        lwr       upr     p adj
## Labour-Conservative           -11.289913 -14.337952 -8.241874 0.0000000
## Liberal Democrat-Conservative  -3.346731  -7.879929  1.186467 0.1932847
## Liberal Democrat-Labour         7.943182   3.268103 12.618261 0.0002144
#Paying attention to the first and last columns, i.e., compared pairs and "p adj" shows the adjusted p-values for each comparison (with the null hypothesis that the two groups are equal and the alternative hypothesis that the two groups are different). These adjusted p-values are used to test whether the two groups are significantly different or not. 
#Only 2 adjusted p-values are less than 0.05, and the Liberal Democrat-Conservative parameter is larger, which implies that these two groups are equal with respect to voting age.
#We see that the confidence intervals do cross the zero line, which indicate that 1 group is significantly different.


# To also find out the effect of the difference we calculate this parameter:
kruskal_effsize(ESS, agea ~ prtvtdgb)
## # A tibble: 1 × 5
##   .y.       n effsize method  magnitude
## * <chr> <int>   <dbl> <chr>   <ord>    
## 1 agea    731  0.0884 eta2[H] moderate
# From the results we can see that the obtained effect size is moderate, i.e. although there is a difference between the variables, it is not large.


#The results of the tests can also be presented in 1 graph:
ggbetweenstats(
  data = ESS,
  x = prtvtdgb,
  y = agea,
  type = "nonparametric", # ANOVA or Kruskal-Wallis
  var.equal = TRUE, # ANOVA or Welch ANOVA
  plot.type = "box",
  pairwise.comparisons = TRUE,
  pairwise.display = "significant",
  centrality.plotting = FALSE,
  bf.message = FALSE
)
## Warning in min(x): у 'min' нет не пропущенных аргументов; возвращаю Inf
## Warning in max(x): у 'max' нет не пропущенных аргументов; возвращаю -Inf

***Conclusion: Based on the work done we can conclude that people who vote for parties have differences in the age category, but not in all of them. To be more specific this appears to be the case: - “Conservative” and “Liberal Democrat” parties have no big differences - The Conservative and Labor, as well as Labor and Liberal Democrat parties have large differences in the age of respondents who voted. Nevertheless, this effect of difference does not affect the results much, which was also measured by means of tests. Thus, we conclude that English people who are older prefer to choose “Conservative” and “Liberal Democrat”, but younger people prefer to stick to “Labor” party.