EXPLORACIÓN BIVARIADA


SESIÓN 6 - EXPLORACIÓN BIVARIADA

Apuntes de Hugo: http://rpubs.com/HUGO-ALONSO-VALVERDE/544746

EXPLORACIÓN BIVARIADA

Combina todas las categorías posibles.

VARIABLE CATEGÓRICA - NUMÉRICA

  1. CARGA DE DATA
library(rio)

linkGIT="https://github.com/JoseManuelMagallanes/Estadistica_Para_AnalisisPolitico/raw/master/hsb.sav"
data=import(linkGIT)

str(data,strict.width = 'cut',witch=50)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : num  1 2 3 4 5 6 7 8 9 10 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ SEX   : num  2 1 2 2 2 1 1 2 1 2 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ RACE  : num  2 2 2 2 2 2 2 2 2 2 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ SES   : num  1 1 1 2 2 2 1 1 2 1 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ SCTYP : num  1 1 1 1 1 1 1 1 1 1 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ HSP   : num  3 2 2 3 3 2 1 1 1 1 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CAR   : num  10 2 9 15 1 11 10 9 9 11 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
  1. FORMATEAR

Lea la metadata,y de formato:

data$ID=as.character(data$ID) #queremos cambiar a chr esos números

data[,c(2,3,5,6,10)]=lapply(data[,c(2,3,5,6,10)],as.factor) #queremos cambiar a texto esos números

data$SES=as.ordered(data$SES) #queremos volver ordinal la categoría socioeconómica

Ahora:

str(data,strict.width="cut",width=50)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : chr  "1" "2" "3" "4" ...
##  $ SEX   : Factor w/ 2 levels "1","2": 2 1 2 2 2..
##  $ RACE  : Factor w/ 4 levels "1","2","3","4": 2..
##  $ SES   : Ord.factor w/ 3 levels "1"<"2"<"3": 1..
##  $ SCTYP : Factor w/ 2 levels "1","2": 1 1 1 1 1..
##  $ HSP   : Factor w/ 3 levels "1","2","3": 3 2 2..
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CAR   : Factor w/ 17 levels "1","2","3","4",...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55..
##   ..- attr(*, "format.spss")= chr "F5.2"

Tarea: Analizar READING y SCIENCE, por sexo y nivel socioeconómico. Escribir conclusiones.

I. READING

significativa cuando la prob. es menor que 0.5.

I.1 RDG y SEX

f1=formula(RDG ~ SEX)
aggregate(f1, data,mean) 
##   SEX      RDG
## 1   1 52.36300
## 2   2 51.51682
library(knitr)
tablag= aggregate(f1, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:
library(knitr)

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SEX W Prob
1 0.9784886 0.0003866
2 0.9824176 0.0004953
library(ggpubr)
## Loading required package: ggplot2
## Loading required package: magrittr
ggqqplot(data=data,x="RDG") + facet_grid(. ~ SEX)

Como no hay normalidad, vamos por camino NO parametrico:

PRUEBA NO PARAMÉTRICA:

wilcox sirve SOLO para variables de dos valores (ejm: hombre mujer) notch es la apertura son los dientes ( >< >< ><), si se separan la diferencia es significativo, si se juntan no.

wilcox.test(f1,data)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  RDG by SEX
## W = 46426, p-value = 0.3962
## alternative hypothesis: true location shift is not equal to 0
ggplot(data=data, aes(x=SEX, y=RDG)) + geom_boxplot(notch = T)

Concluyendo que NO hay diferencia de medias.

I.2 RDG y SES

PRUEBA PARAMÉTRICA:

kruskal.test cuando hay DOS O MÁS VARIABLES

f2=formula(RDG ~ SES)
aggregate(f2, data,mean) 
##   SES      RDG
## 1   1 47.33597
## 2   2 51.92542
## 3   3 55.77593
library(knitr)
tablag=aggregate(f2, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SES W Prob
1 0.9533579 0.0001203
2 0.9841816 0.0022243
3 0.9814021 0.0282263

Aqui lo puedes graficar:

library(ggpubr)
ggqqplot(data=data,x="RDG") + facet_grid(. ~ SES)

Opcion No Paramétrica para politomica:

kruskal.test(f2,data)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  RDG by SES
## Kruskal-Wallis chi-squared = 52.583, df = 2, p-value = 3.818e-12

e-12 = 10 a la menos doce

Mismo resultado.

Visualmente:

ggplot(data=data, aes(x=SES, y=RDG)) + geom_boxplot(notch = T)

El valor medio que se alejaria seria el SES=1 de todos los demas.

I. SCIENCE

I.1 SCI y SEX

f1=formula(SCI ~ SEX)
aggregate(f1, data,mean) 
##   SEX      SCI
## 1   1 53.23004
## 2   2 50.53884
library(knitr)
tablag=aggregate(f1, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SEX W Prob
1 0.9787394 0.0004268
2 0.9798800 0.0001525

Aqui lo puedes graficar:

library(ggpubr)
ggqqplot(data=data,x="SCI") + facet_grid(. ~ SEX)

Como no hay normalidad, vamos por camino NO parametrico:

wilcox.test(f1,data)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  SCI by SEX
## W = 51631, p-value = 0.0009173
## alternative hypothesis: true location shift is not equal to 0

Visualmente:

ggplot(data=data, aes(x=SEX, y=SCI)) + geom_boxplot(notch = T)

Concluyendo que SI hay diferencia de medias.

I.2 SCI y SES

f2=formula(SCI ~ SES)
aggregate(f2, data,mean) 
##   SES      SCI
## 1   1 47.30576
## 2   2 51.93010
## 3   3 55.28025
library(knitr)
tablag=aggregate(f2, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SES W Prob
1 0.9773277 0.0205115
2 0.9833695 0.0015284
3 0.9574177 0.0000744

Aqui lo puedes graficar:

library(ggpubr)
ggqqplot(data=data,x="SCI") + facet_grid(. ~ SES)

Ningun grupo es normal. Vamos por no parametrico:

kruskal.test(f2,data)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  SCI by SES
## Kruskal-Wallis chi-squared = 52.806, df = 2, p-value = 3.415e-12

Hay diferencias!

Visualmente:

ggplot(data=data, aes(x=SES, y=SCI)) + geom_boxplot(notch = T)

Los tres grupos se diferencian.

EXPLORACION BIVARIADA DESDE TABLAS WEB

1. Carga de data:

Para esta sesión usaremos estos datos:

Traigamosla desde Google:

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ_VNceU6ncsQs-_KFvkQsv2XqYKRCMyRYCDYQFosH5bo6Yt-l1gE8ZRdP44m4Rh8lQB2nOY-Y-p0ZP/pub?gid=0&single=true&output=csv"

hsb=read.csv(link, stringsAsFactors = F)

2. EXPLOREMOS

¿Qué tenemos?

Esto es lo R ha traido:

str(hsb)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ SEX   : int  2 1 2 2 2 1 1 2 1 2 ...
##  $ RACE  : int  2 2 2 2 2 2 2 2 2 2 ...
##  $ SES   : int  1 1 1 2 2 2 1 1 2 1 ...
##  $ SCTYP : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ HSP   : int  3 2 2 3 3 2 1 1 1 1 ...
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
##  $ CAR   : int  10 2 9 15 1 11 10 9 9 11 ...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...

3. PRE PROCESAMIENTO:

No se puede empezar el análisis sin adecuar la data a la metadata

La data tiene que reformatearse segun lo que indica la metadata:

Los cambios que se necesitan son:

# id como texto (pues no es variable, sino "identificador")
hsb$ID=as.character(hsb$ID)

# estas variables como CATEGORICAS NOMINALES
hsb[,c(2,3,5,6,10)]=lapply(hsb[,c(2,3,5,6,10)],as.factor)

# estas variables como CATEGORICAS ORDINALES
hsb$HSP=as.ordered(hsb$HSP)

Note que el formateo NO INCLUYO RECODIFICACIÓN. La recodificación es necesaria cuando la variable categórica presenta etiquetas como categorías (vera ese caso cuando trabaje el Indice de Democracia, para las variables tipo de regimen y continente).

Note además que NO todas las columnas serán variables, otras sera identificadores o claves o keys. Los identificadores deben permanecer como texto (char).

Ahora veamos nueva estructura:

str(hsb,strict.width="cut",width=50)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : chr  "1" "2" "3" "4" ...
##  $ SEX   : Factor w/ 2 levels "1","2": 2 1 2 2 2..
##  $ RACE  : Factor w/ 4 levels "1","2","3","4": 2..
##  $ SES   : int  1 1 1 2 2 2 1 1 2 1 ...
##  $ SCTYP : Factor w/ 2 levels "1","2": 1 1 1 1 1..
##  $ HSP   : Ord.factor w/ 3 levels "1"<"2"<"3": 3..
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0..
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -..
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33..
##  $ CAR   : Factor w/ 17 levels "1","2","3","4",...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62..
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64..
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48..
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4..
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55..

4. Probando HIPOTESIS a nivel bivariado

Lo clave para probar hipotesis es saber la hipótesis nula de la prueba estadística que le toque hacer.

la prueba estadística depende de saber si la variable numérica a analizar se distribuye normalmente:

Por ejemplo, para todos nuestros ejemplos, usaremos a MATH como nuestra variable numérica de interés. Veamos la distribuición de esta variable:

library(ggplot2)

base=ggplot(data=hsb, aes(x=MATH))
base + geom_histogram(bins = 20)

Usaremos tests y graficas para comprobar si MATH se distribuye (u otra variabe numerica) tiene una distribución sufientemente cercana a la normal. El test de normalidad a utilizar será el de Shapiro Wilk, cuya hipotesis nula es que la variable se distribuye normalmente. Recuerda que si hay normalidad se usarán técnicas paramétricas, si no la hay, las NO paramétricas.

IMPORTANTE: Todas las hipotesis nulas serán rechazadas si el test aplicado nos devuelve un p-valor (p-value / prob) menor a 0.05. Cuando un test de hipotesis tiene ese valor, se dice que significativo.

a. Tipo 1: NUM-DICO

Aqui plantearemos hipótesis entre una variable numerica y una variable categorica dicotómica (solo dos niveles).

  • HIPOTESIS NULA o H0: Los promedios de las variable numerica en cada grupo de la dicotómica no se diferencian.

Si tenemos que estos son los promedios de matematicas para hombres y mujeres:

f1=formula(MATH ~ SEX)
aggregate(f1, hsb,mean) 
##   SEX     MATH
## 1   1 52.34542
## 2   2 51.43456

Podemos inferir que a los hombres les va mejor en MATH?

  1. Paso 1: Decidiendo si es no no paramétrico

Usemos el método gráfico:

library(ggpubr)

ggqqplot(data=hsb,x="MATH") + facet_grid(. ~ SEX)

Si los puntos se alejan mucho de la diagonal, se aleja de la normalidad.

Como es dificil hacerlo visualmente siempre, podemos usar el test de Shapiro-Wilk, que nos reporta la probabilidad que los datos tengan esa distribución.

# funcion ad-hoc
normalidadTest=function(x) {y =shapiro.test(x); 
                            c(y$statistic, y$p.value)}
# calculando
resultado= aggregate(f1, hsb,
                     FUN = normalidadTest) 


# mostrando resultado
library(knitr)

shapiroTest=as.data.frame(resultado[,2])
names(shapiroTest)=c("SW_Statistic","Probabilidad")
kable(cbind(resultado[1],shapiroTest))
SEX SW_Statistic Probabilidad
1 0.9837903 0.0034565
2 0.9790040 0.0001031

El test nos dice que la probabilidad que la variable MATH se comporte como la curva normal es muy baja (considera bajo si es menor a 0.05). Se rechaza la hipótesis que MATH tiene distribución normal en cada nivel de SEXO.

2. Aplicando TEST para aceptar o rechazar la H0:

Ya sabemos que lo que corresponde utilizar, si ya sabemos que no es NORMAL, es alguna prueba no paramétrica que me informe si los promedios difieren segun grupo. Pero veamos ambos tipos de pruebas:

  • Opcion Paramétrica para dicotómica:

Si hay normalidad usa la prueba t:

t.test(f1,hsb)
## 
##  Welch Two Sample t-test
## 
## data:  MATH by SEX
## t = 1.1722, df = 560.59, p-value = 0.2416
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -0.6154067  2.4371360
## sample estimates:
## mean in group 1 mean in group 2 
##        52.34542        51.43456

Esta prueba informa la probabilidad que la media de MATH sea la misma en ambos grupos de SEX. Como ves, el p-value es mayor a 0.05, por lo que aceptamos la H0 de la prueba t.

  • Opcion No Paramétrica para dicotómica:

Si no hay normalidad usa la prueba Mann-Whitney:

# el test de wilcoxon devuelve Mann-Whitney 
# al recibir "f1"
wilcox.test(f1,hsb)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  MATH by SEX
## W = 46789, p-value = 0.3086
## alternative hypothesis: true location shift is not equal to 0

Igualmente, el p-value sale NO signficativo. SE acepta la H0 del Mann-Whitney.

b. Tipo 2: NUM-POLI

Aqui plantearemos hipótesis entre una variable numerica y una variable categorica politómica (más de dos niveles).

  • HIPOTESIS NULA o H0: Los promedios de las variable numerica en cada grupo de la politómica no se diferencian. Si tenemos que estos son los promedios de matematicas según programa escolar:
f2=formula(MATH ~ HSP)
aggregate(f2, hsb,mean) 
##   HSP     MATH
## 1   1 55.81071
## 2   2 49.09172
## 3   3 46.26803

Podemos inferir que a los alumnos del programa general les va mejor en MATH?

1. Paso 1: Decidiendo si es no no paramétrico

Usemos el método gráfico:

library(ggpubr)
ggqqplot(data=hsb,x="MATH") + facet_grid(. ~ HSP)

Ahora hagamos el test de Shapiro Wilk

# calculando
resultado= aggregate(f2, hsb,
                     FUN = normalidadTest) 


# mostrando resultado
library(knitr)

shapiroTest=as.data.frame(resultado[,2])
names(shapiroTest)=c("SW_Statistic","Probabilidad")
kable(cbind(resultado[1],shapiroTest))
HSP SW_Statistic Probabilidad
1 0.9888836 0.0187048
2 0.9810514 0.0423975
3 0.9512192 0.0000496

Como al menos una tiene probabilidad menor a 0.05, debemos ir por el camino no paramétrico.

2. Aplicando TEST para aceptar o rechazar la H0:

  • Opcion Paramétrica para politomica:

Aquí corresponde la pruea F de Schnedecor, conocida tambien como one-way ANOVA:

summary(aov(f2, data=hsb))
##              Df Sum Sq Mean Sq F value Pr(>F)    
## HSP           2  10515    5258   73.72 <2e-16 ***
## Residuals   597  42579      71                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Los astericos indican si el H0 es significativo. Podemos rechazarlo, de ahi que al menos un promedio difiere de los demás. Tratemos de detectar las diferencias:

library(ggpubr)
ggerrorplot(hsb, x = "HSP", 
            y = "MATH", 
            desc_stat = "mean_ci"
            )

El nivel 1 se diferenciaría de los demás.

  • Opcion No Paramétrica para politomica:

Aquí puedes usar la prueba de Kruskal-Wallis:

kruskal.test(f2,hsb)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  MATH by HSP
## Kruskal-Wallis chi-squared = 121.26, df = 2, p-value < 2.2e-16

Aqui no muestra asteriscos, pero la probabilidad (p-value) es también menor a 0.05.

Visualmente:

ggplot(data=hsb, aes(x=HSP, y=MATH)) + geom_boxplot(notch = T)

En este caso, se ha puesto un ‘notch’ al boxplot. Si los notches se intersectan, se asume igualdad de medianas, de ahí que la opcion 1 es diferente a las demás.

Tarea: Analizar WRITING, por sexo y nivel socioeconómico. Escribir conclusiones.

SESIÓN 7 - PRÁCTICA DIRIGIDA DE EXPLORACIÓN BIVARIADA

CARGANDO Y PRE PROCESANDO LA DATA

library(htmltab)

link='https://en.wikipedia.org/wiki/Democracy_Index'

path='//*[@id="mw-content-text"]/div/table[2]'

demo=htmltab(doc = link, which = path)

names(demo)
##  [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"
  • Mejorando nombres
newNames=c("Rank","Country","Score","Electoral","Functioning","Participation","Culture","Civilliberties","RegimeType","Continent")

names(demo)=newNames

str(demo)
## 'data.frame':    167 obs. of  10 variables:
##  $ Rank          : chr  "1" "2" "3" "4" ...
##  $ Country       : chr  " Norway" " Iceland" " Sweden" " New Zealand" ...
##  $ Score         : chr  "9.87" "9.58" "9.39" "9.26" ...
##  $ Electoral     : chr  "10.00" "10.00" "9.58" "10.00" ...
##  $ Functioning   : chr  "9.64" "9.29" "9.64" "9.29" ...
##  $ Participation : chr  "10.00" "8.89" "8.33" "8.89" ...
##  $ Culture       : chr  "10.00" "10.00" "10.00" "8.13" ...
##  $ Civilliberties: chr  "9.71" "9.71" "9.41" "10.00" ...
##  $ RegimeType    : chr  "Full democracy" "Full democracy" "Full democracy" "Full democracy" ...
##  $ Continent     : chr  "Europe" "Europe" "Europe" "Oceania" ...

Mejorando datos con problemas de formato

  • Evitando los espacios en blanco:
# siempre que venga como texto, eliminar espacios en blanco

demo[,]=lapply(demo[,],trimws,whitespace= '[\\h\\v]')
  • Convirtiendo en variabe catégorica nominal:
demo$Continent=as.factor(demo$Continent)
  • Convirtiendo en variable categórica ordinal:

  • Viendo niveles (levels)

table(demo$RegimeType)
## 
##    Authoritarian Flawed democracy   Full democracy    Hybrid regime 
##               53               55               20               39
  • Ajustando niveles:
ordenOK=c('Authoritarian','Hybrid regime','Flawed democracy','Full democracy')

demo$RegimeType=ordered(demo$RegimeType,levels=ordenOK)
  • Convirtiendo en variable numérica:
demo[,-c(2,9,10)]=lapply(demo[,-c(2,9,10)],as.numeric)
  • Explorando valores perdidos:
demo[!complete.cases(demo),]
##  [1] Rank           Country        Score          Electoral     
##  [5] Functioning    Participation  Culture        Civilliberties
##  [9] RegimeType     Continent     
## <0 rows> (or 0-length row.names)
  • Desechar columna con perdidos (si no fuera importante)
demo$Rank=NULL
  • Pedir resumen estadístico:
summary(demo)
##    Country              Score         Electoral       Functioning   
##  Length:167         Min.   :1.080   Min.   : 0.000   Min.   :0.000  
##  Class :character   1st Qu.:3.545   1st Qu.: 3.000   1st Qu.:2.860  
##  Mode  :character   Median :5.690   Median : 6.580   Median :5.000  
##                     Mean   :5.479   Mean   : 5.903   Mean   :4.885  
##                     3rd Qu.:7.175   3rd Qu.: 9.170   3rd Qu.:6.790  
##                     Max.   :9.870   Max.   :10.000   Max.   :9.640  
##  Participation      Culture       Civilliberties              RegimeType
##  Min.   : 1.11   Min.   : 1.250   Min.   : 0.000   Authoritarian   :53  
##  1st Qu.: 3.89   1st Qu.: 4.380   1st Qu.: 3.530   Hybrid regime   :39  
##  Median : 5.56   Median : 5.630   Median : 5.880   Flawed democracy:55  
##  Mean   : 5.25   Mean   : 5.594   Mean   : 5.768   Full democracy  :20  
##  3rd Qu.: 6.67   3rd Qu.: 6.250   3rd Qu.: 8.240                        
##  Max.   :10.00   Max.   :10.000   Max.   :10.000                        
##          Continent 
##  Africa       :50  
##  Asia         :42  
##  Europe       :45  
##  North America:14  
##  Oceania      : 4  
##  South America:12

PREGUNTAS

1) Analizar la relacion entre el score (indice) y el continente

  1. Determinando tipo de relación: A partir del resumen estadístico se determina que es Numerica - Categórica

  2. Determinando si la variable numerica se comporta de manera normal:

library(ggpubr)

ggqqplot(data=demo,x="Score") + facet_grid(. ~ Continent)

2) Analizar la relacion entre Continente y Tipo de Regimen

  1. Determinando tipo de relación: A partir del resumen estadístico se determina que es Categórica - Categórica

  2. Construir tabla de contingencia:

Columna=demo$Continent
Fila=demo$RegimeType

(t=table(Fila,Columna))
##                   Columna
## Fila               Africa Asia Europe North America Oceania South America
##   Authoritarian        26   20      4             2       0             1
##   Hybrid regime        15    9      9             4       1             1
##   Flawed democracy      8   13     18             6       1             9
##   Full democracy        1    0     14             2       2             1

Mostrar porcentajes:

# marginal por columna (suma 1 por columna, no por fila)
prop_t=prop.table(t,margin = 2)
round(prop_t,2)
##                   Columna
## Fila               Africa Asia Europe North America Oceania South America
##   Authoritarian      0.52 0.48   0.09          0.14    0.00          0.08
##   Hybrid regime      0.30 0.21   0.20          0.29    0.25          0.08
##   Flawed democracy   0.16 0.31   0.40          0.43    0.25          0.75
##   Full democracy     0.02 0.00   0.31          0.14    0.50          0.08
library("gplots")
## 
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
## 
##     lowess
# nota que uso la funcion "t()":
balloonplot(t(prop_t), main ="Tabla",
            label = T, show.margins = FALSE)

  1. Determinar si hay indepencia entre las variables estadistica:
chisq.test(t,simulate.p.value = T)
## 
##  Pearson's Chi-squared test with simulated p-value (based on 2000
##  replicates)
## 
## data:  t
## X-squared = 64.445, df = NA, p-value = 0.0004998
  1. Si no hay independencia, calcular intensidad:
library(oii)
association.measures(Fila,Columna)
## Chi-square-based measures of association:
##    Phi:                      0.621 
##    Contingency coefficient:  0.528 
##    Cramer's V:               0.359 
## 
## Ordinal measures of association:
##    Total number of pairs:   13861 
##    Concordant pairs:        6064   ( 43.75 %)
##    Discordant pairs:        1872   ( 13.51 %)
##    Tied on first variable:  2686   ( 19.38 %)
##    Tied on second variable: 2131   ( 15.37 %)
##    Tied on both variables:  1108   ( 7.99 %)
## 
##    Goodman-Kruskal Gamma: 0.528 
##    Somers' d (col dep.):  0.416 
##    Kendall's tau-b:       0.405 
##    Stuart's tau-c:        0.401

El Coeficiente de contingencia o Cramer sugieren una intensidad relevante (mayor a 0.3).

  1. Analizar la relacion entre Participacion Politica y todas las otras componentes del indice (no analizar el indice)
  1. Determinando tipo de relación: A partir del resumen estadístico se determina que es Numerica - Numérica

  2. Determinando si la variable numerica se comporta de manera normal:

library(dlookr)
## Loading required package: mice
## Loading required package: lattice
## 
## Attaching package: 'mice'
## The following objects are masked from 'package:base':
## 
##     cbind, rbind
## Registered S3 method overwritten by 'xts':
##   method     from
##   as.zoo.xts zoo
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Registered S3 methods overwritten by 'car':
##   method                          from
##   influence.merMod                lme4
##   cooks.distance.influence.merMod lme4
##   dfbeta.influence.merMod         lme4
##   dfbetas.influence.merMod        lme4
## Warning in fun(libname, pkgname): couldn't connect to display ":0"
## 
## Attaching package: 'dlookr'
## The following object is masked from 'package:base':
## 
##     transform
normality(demo[,c(3:7)])
## Warning: `cols` is now required.
## Please use `cols = c(statistic)`
## # A tibble: 5 x 4
##   vars           statistic  p_value sample
##   <chr>              <dbl>    <dbl>  <dbl>
## 1 Electoral          0.865 4.14e-11    167
## 2 Functioning        0.977 6.52e- 3    167
## 3 Participation      0.981 2.12e- 2    167
## 4 Culture            0.964 2.69e- 4    167
## 5 Civilliberties     0.954 2.87e- 5    167
  1. Calculando correlaciones solicitadas:
library(ggpubr)
p1=ggscatter(demo, 
          x = "Electoral", y = "Participation",
          cor.coef = TRUE, 
          cor.method = "spearman") 
p2=ggscatter(demo, 
          x = "Functioning", y = "Participation",
          cor.coef = TRUE, 
          cor.method = "spearman")
p3=ggscatter(demo, 
          x = "Culture", y = "Participation",
          cor.coef = TRUE, 
          cor.method = "spearman")
p4=ggscatter(demo, 
          x = "Civilliberties", y = "Participation",
          cor.coef = TRUE, 
          cor.method = "spearman")
# paso 1:
all_ps=ggarrange(p1,p2,p3,p4,
          ncol = 2, nrow = 2) 

# paso 2
annotate_figure(all_ps,
               top = text_grob("Correlacion con PARTICIPATION", 
                               color = "blue", 
                               face = "bold", 
                               size = 14))

Sin los gráficos lo puedes ver asi:

dataForCor=demo[,c(5,3,4,6,7)]
#cor.test(dataForCor[,-1], dataForCor[,1],method = "spearman")
lapply(dataForCor[,-1],
       cor.test,y=dataForCor[,1],method="spearman",exact=FALSE)
## $Electoral
## 
##  Spearman's rank correlation rho
## 
## data:  X[[i]] and dataForCor[, 1]
## S = 183345, p-value < 2.2e-16
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##       rho 
## 0.7637965 
## 
## 
## $Functioning
## 
##  Spearman's rank correlation rho
## 
## data:  X[[i]] and dataForCor[, 1]
## S = 219483, p-value < 2.2e-16
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##       rho 
## 0.7172393 
## 
## 
## $Culture
## 
##  Spearman's rank correlation rho
## 
## data:  X[[i]] and dataForCor[, 1]
## S = 389588, p-value = 7.43e-12
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##       rho 
## 0.4980935 
## 
## 
## $Civilliberties
## 
##  Spearman's rank correlation rho
## 
## data:  X[[i]] and dataForCor[, 1]
## S = 177123, p-value < 2.2e-16
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##       rho 
## 0.7718116