library(htmltab)
links=list(web="https://en.wikipedia.org/wiki/Democracy_Index",
xpath ='//*[@id="mw-content-text"]/div/table[2]/tbody')
democratos<- htmltab(doc = links$web, which =links$xpath)
2.1. Inspeccion:
Veamos la estructura
str(democratos)
## 'data.frame': 167 obs. of 10 variables:
## $ Rank >> Rank : chr "1" "2" "3" "4" ...
## $ Country >> Country : chr " Norway" " Iceland" " Sweden" " New Zealand" ...
## $ Score >> Score : chr "9.87" "9.58" "9.39" "9.26" ...
## $ Electoral processand pluralism >> Electoral processand pluralism: chr "10.00" "10.00" "9.58" "10.00" ...
## $ Functioning ofgovernment >> Functioning ofgovernment : chr "9.64" "9.29" "9.64" "9.29" ...
## $ Politicalparticipation >> Politicalparticipation : chr "10.00" "8.89" "8.33" "8.89" ...
## $ Politicalculture >> Politicalculture : chr "10.00" "10.00" "10.00" "8.13" ...
## $ Civilliberties >> Civilliberties : chr "9.71" "9.71" "9.41" "10.00" ...
## $ Regimetype >> Regimetype : chr "Full democracy" "Full democracy" "Full democracy" "Full democracy" ...
## $ Continent >> Continent : chr "Europe" "Europe" "Europe" "Oceania" ...
Nombres de variables
names(democratos)
## [1] "Rank >> Rank"
## [2] "Country >> Country"
## [3] "Score >> Score"
## [4] "Electoral processand pluralism >> Electoral processand pluralism"
## [5] "Functioning ofgovernment >> Functioning ofgovernment"
## [6] "Politicalparticipation >> Politicalparticipation"
## [7] "Politicalculture >> Politicalculture"
## [8] "Civilliberties >> Civilliberties"
## [9] "Regimetype >> Regimetype"
## [10] "Continent >> Continent"
2.2. Pre procesamiento:
Nombres sin espacios
library(stringr)
names(democratos)=str_split(names(democratos)," ",simplify = T)[,1]
Nombres sin simbolos “raros”
names(democratos)=str_replace_all(names(democratos), "[^[:ascii:]]", "")
Valores del data frame sin simbolos “raros”
democratos[,]=lapply(democratos[,], str_replace_all,"[^[:ascii:]]","")
Eliminar columnas que no se usaran y que se podrian recalcular
democratos$Rank=NULL
Recuperar numeros
library(readr)
democratos[,c(2:7)]=lapply(democratos[,c(2:7)],parse_number)
Configurar Categorias
table(democratos$Regimetype)
##
## Authoritarian Flawed democracy Full democracy Hybrid regime
## 53 55 20 39
Recoge la cantidad que existen en cada tipo de régimen. Los niveles son: Authoritarian, Hybrid regime, Flawed democracy, Full democracy.
ordenOK=c("Authoritarian","Hybrid regime", "Flawed democracy","Full democracy")
democratos$Regimetype=factor(democratos$Regimetype, levels=ordenOK,ordered = TRUE)
Esto permite que los tipos de gobierno se ordenen ascendentemente
democratos$Continent=as.factor(democratos$Continent)
str(democratos)
## 'data.frame': 167 obs. of 9 variables:
## $ Country : chr "Norway" "Iceland" "Sweden" "New Zealand" ...
## $ Score : num 9.87 9.58 9.39 9.26 9.22 9.15 9.15 9.14 9.09 9.03 ...
## $ Electoral : num 10 10 9.58 10 10 9.58 9.58 10 10 9.58 ...
## $ Functioning : num 9.64 9.29 9.64 9.29 9.29 7.86 9.64 8.93 8.93 9.29 ...
## $ Politicalparticipation: num 10 8.89 8.33 8.89 8.33 8.33 7.78 8.33 7.78 7.78 ...
## $ Politicalculture : num 10 10 10 8.13 9.38 10 8.75 8.75 8.75 9.38 ...
## $ Civilliberties : num 9.71 9.71 9.41 10 9.12 10 10 9.71 10 9.12 ...
## $ Regimetype : Ord.factor w/ 4 levels "Authoritarian"<..: 4 4 4 4 4 4 4 4 4 4 ...
## $ Continent : Factor w/ 6 levels "Africa","Asia",..: 3 3 3 5 3 3 4 3 5 3 ...
library(DescTools)
Median(democratos$Regimetype)
## [1] Hybrid regime
## 4 Levels: Authoritarian < Hybrid regime < ... < Full democracy
Tipo de regimen representaivo = Median (ORDINAL)
library(questionr)
library(magrittr)
OrdDf=freq(democratos$Regimetype,total = F,exclude = c(NA),cum = T) %>% data.frame()
OrdDf=data.frame(row.names(OrdDf),OrdDf,row.names = NULL)
names(OrdDf)=c("Categoria","Conteo", "Porcentaje", "Porcentaje Acumulado")
OrdDf
## Categoria Conteo Porcentaje Porcentaje Acumulado
## 1 Authoritarian 53 31.7 31.7
## 2 Hybrid regime 39 23.4 55.1
## 3 Flawed democracy 55 32.9 88.0
## 4 Full democracy 20 12.0 100.0
3/4 que es 75% si superan el régimen híbrido porque están por el Flawed democracy
3.1. ¿Cual es el valor representativo de Continente?
Mode(democratos$Continent)
## [1] "Africa"
Valor representativo de Continente = Mode (NOMINAL)
3.2. ¿Es el valor representativo de continente muy prominente? (quizas otros continentes no envian informacion?)
tablaContinente=prop.table(table(democratos$Continent))
Herfindahl(tablaContinente)
## [1] 0.238266
< 0.01 : indica que la moda no es significativa, las categorias tienen pesos similares. < 0.15 : indica que la moda no es significativa, varias categorias tienen pesos similares. entre 0.15 - 0.25: hay una moda. 0.25: La moda se diferencia de los demas Si es> 3: es prominente
Permite ver si el valor del continente es prominente.
No se puede hallar porque es nominal.
library(ggplot2)
base = ggplot(data=OrdDf,aes(x=Categoria , y=Conteo))
bar1 = base + geom_bar(stat='identity')
bar1 + scale_x_discrete(limits =OrdDf$Categoria)
library(ggplot2)
basep=ggplot(data=democratos, aes(y=as.numeric(Regimetype)))
basep + geom_boxplot() + coord_flip()
La cola está a la izquierda Hay asimetría.
¿Te das cuenta por que hay asimetría? Si la media es mayor que la mediana la asimetría tiende a ser positiva (cola a la derecha). Hay tendencia a la asimetría negativa (cola a la izquierda) cuando la mediana es mayor que la media. Aquí se nota claramente que hay asimetría, pero podemos confirmarla calculando el coeficiente respectivo:
summary(democratos$Score)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.080 3.545 5.690 5.479 7.175 9.870
basen=ggplot(data=democratos,aes(x=Score))
basen + geom_histogram(bins=10)
Skew(democratos$Score,conf.level = 0.05)
## skew lwr.ci upr.ci
## -0.07107195 -0.07082602 -0.05827368
Gini(democratos$Score)
## [1] 0.2316285
No, porque la igualdad plena es 1 y la desigualdad no hay si es 0.
library(ggplot2)
library(gglorenz)
## Registered S3 methods overwritten by 'ineq':
## method from
## plot.Lc DescTools
## lines.Lc DescTools
ggplot(democratos,aes(x=Score))+ gglorenz::stat_lorenz(color='purple') +
geom_abline(linetype = "dashed") + coord_fixed() +
labs(x = "% Paises ordenados por Indice de Democracia",
y = "% Acumulado de Puntuación de ID",
title = "Relación pais/Indice de democracia",
caption = "Fuente: The Economist") +
scale_y_continuous(breaks=seq(0,1,0.15)) +
scale_x_continuous(breaks=seq(0,1,0.2))
Se podría decir que el 80% de los países tiene una puntuación de 68.5%
9.1. ¿Hay atipicos en el score de democracia?
q3=quantile(democratos$Score,0.75)
q1=quantile(democratos$Score,0.25)
umbralAlto= q3+1.5*IQR(democratos$Score)
umbralBajo= q1-1.5*IQR(democratos$Score)
9.2. ¿Ausencia de atipicos grandes?
democratos[democratos$Score>=umbralAlto,]
## [1] Country Score Electoral
## [4] Functioning Politicalparticipation Politicalculture
## [7] Civilliberties Regimetype Continent
## <0 rows> (or 0-length row.names)
No hay atípico grande
9.3. ¿Ausencia de atipicos pequeños?
democratos[democratos$Score<=umbralBajo,]
## [1] Country Score Electoral
## [4] Functioning Politicalparticipation Politicalculture
## [7] Civilliberties Regimetype Continent
## <0 rows> (or 0-length row.names)
No hay atípico pequeño