Chargement des librairies

library(ggplot2)
library(plyr)
library(lessR)
## 
## lessR 3.9.9  feedback: gerbing@pdx.edu  web: lessRstats.com/new
## ---------------------------------------------------------------
## > d <- Read("")   Read text, Excel, SPSS, SAS, or R data file
##   d is default data frame, data= in analysis routines optional
## 
## Many vignettes show by example how to use lessR. Topics are
## read, write, & manipulate data, graphics, means & models,
##   factor analysis, & customization. Two ways to view.
## Enter:  browseVignettes("lessR")
## Visit:  https://CRAN.R-project.org/package=lessR
## 
## Attaching package: 'lessR'
## The following object is masked from 'package:plyr':
## 
##     .
library(arm)
## Loading required package: MASS
## Loading required package: Matrix
## Loading required package: lme4
## 
## arm (Version 1.12-2, built: 2021-10-15)
## Working directory is /Users/luca/Documents/Enjeux présidentielle
library(stringr)
library(PRROC)

Charger espace de travail et importer données

setwd("~/Documents/Enjeux présidentielle")
data = read.csv("grille_codage.csv",header=T,sep=",")
data = data[-579,] # Enlever ligne totaux

Recodage et création de nouvelles variables

# Basic stats

#head(data)
dim(data)
## [1] 578  42
# code NAs as 0

data[which(data$Tradition..conformité..Conservatisme == "°"),"Tradition..conformité..Conservatisme"] = 0
data$Tradition..conformité..Conservatisme = as.numeric(data$Tradition..conformité..Conservatisme)

# code NAs as 0
sum(is.na(data)) # 10301 valuers manquantes
## [1] 10487
data[is.na(data)] = 0

#recode
names(data)[names(data) == "Honnêteté.éthique..exemplarité"] = "Éthique"
names(data)[names(data) == "Protectionisme.Sécurité"] = "Sécurité"
names(data)[names(data) == "Inquiétude.peur"] = "Inquiétude"
names(data)[names(data) == "EthnocentrismeCommunutarisme"] = "Communautarisme"
names(data)[names(data) == "Tradition..conformité..Conservatisme"] = "Conservatisme"
names(data)[names(data) == "Individualisme.Autonomie"] = "Individualisme"
names(data)[names(data) == "Universalisme.Bienveillance"] = "Universalisme"

length(which(data$Éthique == 1))
## [1] 156
#156
length(which(data$Nostalgie == 1))
## [1] 36
#36
length(which(data$Sécurité == 1))
## [1] 144
#144

# Candidats principaux
data["fillon"] = ifelse(data["Vote2017"] == "Fillon", 1, 0)
data["melenchon"] = ifelse(data["Vote2017"] == "Mélenchon", 1, 0)
data["lepen"] = ifelse(data["Vote2017"] == "Le Pen", 1, 0)
data["macron"] = ifelse(data["Vote2017"] == "Macron", 1, 0)
data["hamon"] = ifelse(data["Vote2017"] == "Hamon", 1, 0)
data["abstention"] = ifelse(data["Vote2017"] == "Abst.", 1, 0)

# Bords politiques 
data["droite"] = ifelse(data["Vote2017"] == "Fillon" | data["Vote2017"] == "Le Pen" | data["Vote2017"] == "Dupont-Aignan"| data["Vote2017"] == "Lassalle"| data["Vote2017"] == "Asselineau", 1, 0)
data["gauche"] = ifelse(data["Vote2017"] == "Mélenchon" | data["Vote2017"] == "Hamon" | data["Vote2017"] == "Poutou"| data["Vote2017"] == "Arthaud", 1, 0)



# Retraite 
retraite = rep(1,dim(data)[1])
for(i in 1:dim(data)[1]){
 retraite[i] = ifelse(str_detect(data$CSP[i], "Ancien") == T,1,0)
 }
data = cbind(data,retraite)

# CSP cadre
data["cadre"] = ifelse(data["CSP"] == "Cadre supérieur", 1, 0)

# Ville > 20k hab. 
data["grande_ville"] = ifelse(data["Population"] >= 20000, 1, 0)

Graphiques

Mise en forme

# Compute col totals
totals = numcolwise(sum)(data)
totals_t = t(totals)
colnames(totals_t) = c("count")  
rows = rownames(totals_t)
totals_t = cbind(rows,totals_t)
totals_t = as.data.frame(totals_t)
totals_t[,2]  = as.numeric(totals_t[,2])
dim(totals_t)
## [1] 42  2
tot = totals_t[-c(1,2,3),]

Valeurs

# Valeurs
valeurs = c("Tolérance.Respect","Communautarisme","Individualisme",
            "Sécurité", "Autoritarisme", "Liberté..Libéralisme",
            "Universalisme", "Éthique",
            "Solidarité.Justice","Conservatisme")
tot_valeurs = tot[valeurs,]
tot_valeurs
##                                      rows count
## Tolérance.Respect       Tolérance.Respect   220
## Communautarisme           Communautarisme    60
## Individualisme             Individualisme   116
## Sécurité                         Sécurité   144
## Autoritarisme               Autoritarisme    33
## Liberté..Libéralisme Liberté..Libéralisme   102
## Universalisme               Universalisme   199
## Éthique                           Éthique   156
## Solidarité.Justice     Solidarité.Justice   264
## Conservatisme               Conservatisme     0
par(mar=c(7,4,4,4))
bar_valeurs <- barplot(tot_valeurs$count, border=F , names.arg=tot_valeurs$rows , 
                  las=2 , 
                  col= c("olivedrab", "lightskyblue", "lightsalmon","khaki3","plum"),
                cex.names=0.8,
                  ylim=c(0,300) , 
                  main="Valeurs")

Humeurs

humeurs = c("Colère","Espoir","Nostalgie",
            "Inquiétude", "Bonheur", "Optimisme",
            "Fierté", "Dégoût",
            "Haine","Pessimisme")

tot_humeurs = tot[humeurs,]
tot_humeurs
##                  rows count
## Colère         Colère    86
## Espoir         Espoir   219
## Nostalgie   Nostalgie    36
## Inquiétude Inquiétude    80
## Bonheur       Bonheur    53
## Optimisme   Optimisme   109
## Fierté         Fierté    44
## Dégoût         Dégoût    55
## Haine           Haine    36
## Pessimisme Pessimisme    40
bar_humeurs <- barplot(tot_humeurs$count, 
                       border=F , 
                       names.arg=tot_humeurs$rows ,
                       cex.names=0.8,
                       las=2 , 
                       col= c("olivedrab", "lightskyblue", "lightsalmon","khaki3","plum") , 
                       ylim=c(0,250) , 
                       main="Humeurs")

Modèles de régression logistique

Éthique

# définition du modèle 
lr_Éthique = glm(Éthique ~  melenchon + macron + Dégoût, family = binomial(link = "logit"), data)
summary(lr_Éthique)
## 
## Call:
## glm(formula = Éthique ~ melenchon + macron + Dégoût, family = binomial(link = "logit"), 
##     data = data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.2621  -0.8678  -0.6792   1.3558   1.7776  
## 
## Coefficients:
##             Estimate Std. Error z value             Pr(>|z|)
## (Intercept)  -1.3493     0.1374  -9.820 < 0.0000000000000002
## melenchon     0.5666     0.2741   2.067              0.03874
## macron        0.6072     0.2188   2.775              0.00552
## Dégoût        0.9391     0.2955   3.178              0.00148
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 674.13  on 577  degrees of freedom
## Residual deviance: 656.83  on 574  degrees of freedom
## AIC: 664.83
## 
## Number of Fisher Scoring iterations: 4
# Trouver la séparation optimale
library(InformationValue)
pred.Éthique = as.numeric(lr_Éthique$fitted.values)
optCutOff_Éthique = optimalCutoff(data$Éthique, pred.Éthique, optimiseFor = "Ones")[1] 
optCutOff_Éthique
## [1] 0.309079
#0.309079

# Analyse ROC
PRROC_Éthique = roc.curve(scores.class0 = pred.Éthique, weights.class0=data$Éthique,
                       curve=TRUE)
plot(PRROC_Éthique)

# Tableau récapitulatif - pouvoir de prédiction du modèle
confusionMatrix(data$Éthique,pred.Éthique, threshold = optCutOff_Éthique)
##     0  1
## 0 245 64
## 1 177 92

Nostalgie

# modèle nostalgie
lr_nostalgie = glm(Nostalgie ~ Méfiance + Fierté, family = binomial(link = "logit"), data)
summary(lr_nostalgie)
## 
## Call:
## glm(formula = Nostalgie ~ Méfiance + Fierté, family = binomial(link = "logit"), 
##     data = data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.1387  -0.2567  -0.2567  -0.2567   2.6189  
## 
## Coefficients:
##             Estimate Std. Error z value             Pr(>|z|)
## (Intercept)  -3.3965     0.2515 -13.507 < 0.0000000000000002
## Méfiance      1.2292     0.3794   3.240               0.0012
## Fierté        2.0757     0.4058   5.115          0.000000314
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 269.59  on 577  degrees of freedom
## Residual deviance: 233.46  on 575  degrees of freedom
## AIC: 239.46
## 
## Number of Fisher Scoring iterations: 6
# find optimal cutoff value
pred.nostalgie = as.numeric(lr_nostalgie$fitted.values)
optCutOff_nostalgie = optimalCutoff(data$Nostalgie, pred.nostalgie, optimiseFor = "Ones")[1] 
optCutOff_nostalgie
## [1] 0.09710565
#0.092652

PRROC_nostalgie = roc.curve(scores.class0 = pred.nostalgie, weights.class0=data$Nostalgie,
                       curve=TRUE)
plot(PRROC_nostalgie)

confusionMatrix(data$Nostalgie,pred.nostalgie, threshold = optCutOff_nostalgie)
##     0  1
## 0 437 16
## 1 105 20

Sécurité

# modèle sécurité
lr_Sécurité = glm(Sécurité ~ droite + Inquiétude + Autoritarisme, family = binomial(link = "logit"), data)
summary(lr_Sécurité)
## 
## Call:
## glm(formula = Sécurité ~ droite + Inquiétude + Autoritarisme, 
##     family = binomial(link = "logit"), data = data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4380  -0.7258  -0.5325  -0.5325   2.0117  
## 
## Coefficients:
##               Estimate Std. Error z value             Pr(>|z|)
## (Intercept)    -1.8818     0.1585 -11.873 < 0.0000000000000002
## droite          0.6822     0.2170   3.143              0.00167
## Inquiétude      1.7823     0.2782   6.407       0.000000000148
## Autoritarisme   2.3366     0.4931   4.739       0.000002151654
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 648.96  on 577  degrees of freedom
## Residual deviance: 540.19  on 574  degrees of freedom
## AIC: 548.19
## 
## Number of Fisher Scoring iterations: 4
# find optimal cutoff value
pred.Sécurité = as.numeric(lr_Sécurité$fitted.values)
optCutOff_Sécurité = optimalCutoff(data$Sécurité, pred.Sécurité, optimiseFor = "Ones")[1] 
optCutOff_Sécurité
## [1] 0.2287946
# 0.229963

# ROC curve
PRROC_Sécurité = roc.curve(scores.class0 = pred.Sécurité, weights.class0=data$Sécurité,curve=TRUE)
plot(PRROC_Sécurité)

# Confusion matrix 
confusionMatrix(data$Sécurité,pred.Sécurité, threshold = optCutOff_Sécurité)
##     0   1
## 0 268  41
## 1 166 103