HIPOTESIS NULA o H0: para numéricas con categóricas (dico o poli) NUM- DICO :Los promedios de las variables numericas en cada grupo de la dicotómica no se diferencian. NUM-POLI Los promedios de las variables numericas en cada grupo de la politómica no se diferencian.
Test para aprobar o aceptar hipótesis
PARAMÉTRICA -DICO:PRUEBA T -POLI:anova o prueba F de Schnedeco
NO PÁRAMÉTRICA -DICO:WILCOX POLI: krustal
Cargo 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","civilliber","regimetype","continent")
#resultado
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" ...
## $ civilliber : 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 (limpiando data)
trimmws, con esto limpio la data de espacios en blanco antes y después del valor.
# siempre que venga como texto, eliminar espacios en blanco
demo[,]=lapply(demo[,],trimws,whitespace = "[\\h\\v]")
demo$continent=as.factor(demo$continent)
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)
demo[,-c(2,9,10)]=lapply(demo[,-c(2,9,10)],as.numeric)
Este mensaje me quiere decir que al hacer la conversión, algunos valores han quedado vacíos, no ha podido convertirlos porque en una celda ha encontrado un valor no numérico.
# estos son:
demo[!complete.cases(demo),]
demo$rank= NULL
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 civilliber 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
#1. Analizar la relacion entre El score (indice) y el continente
Determinando tipo de relación: A partir del resumen estadístico se determina que es Numerica - Categórica Hipótesis: las medias son iguales y se distribuye de manera normal.
Determinando si la variable numerica se comporta de manera normal:
library(ggpubr)
## Loading required package: ggplot2
## Loading required package: magrittr
Loading required package: ggplot2 Loading required package: magrittr
ggqqplot(data=demo,x="score") + facet_grid(. ~ continent)
No es normal. En Sudamérica y en Europa cae la normalidad. Quiere decir que en estos continentes el índice de democracia no se comporta de forma normal. En los demás, masomenos.
f1=formula(score~continent)
# funcion ad-hoc
normalidadTest=function(x) {y =shapiro.test(x);
c(y$statistic, y$p.value)}
# calculando
resultado= aggregate(f1, demo,
FUN = normalidadTest)
# mostrando resultado
library(knitr)
shapiroTest=as.data.frame(resultado[,2])
names(shapiroTest)=c("SW_Statistic","Probabilidad")
kable(cbind(resultado[1],shapiroTest))
| continent | SW_Statistic | Probabilidad |
|---|---|---|
| Africa | 0.9653422 | 0.1487353 |
| Asia | 0.9486915 | 0.0579857 |
| Europe | 0.9370922 | 0.0168389 |
| North America | 0.9740888 | 0.9260364 |
| Oceania | 0.7752667 | 0.0647579 |
| South America | 0.8433322 | 0.0304021 |
Tengo que las medias no son iguales. Ahora quiero saber qué grupo es diferente de los otros. uando es NO paramétrica, uso boxplot.
kruskal.test(f1,demo)
##
## Kruskal-Wallis rank sum test
##
## data: score by continent
## Kruskal-Wallis chi-squared = 52.932, df = 5, p-value = 3.473e-10
Aqui no muestra asteriscos, pero la probabilidad (p-value) es también menor a 0.05.
Visualmente, para saber cuál es diferente a los demás:
ggplot(data=demo, aes(x=continent, y=score)) + geom_boxplot(notch = T)
## notch went outside hinges. Try setting notch=FALSE.
## notch went outside hinges. Try setting notch=FALSE.
Son África y Asia las que se diferencias de los demás.
Determinando tipo de relación: A partir del resumen estadístico se determina que es Categórica - Categórica
Hipótesis: Las variables no tienen correlación.
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)
Determinar si hay indepencia o dependencia entre las variables estadisticas.
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
Como p-value es 0.0004998, por lo tanto, es significativo. Se rechaza la hipótesis, por lo tanto, la variables tienen correlación. Esto me quiere decir que lo más probable es que según el continente donde vivas varía el nivel de democracia. Entonces digo que hay dependencia entre las variables estadísticas.
Si el p valor hubiese sido mayor que 0.05, entonces no hubiese sido significativo, lo que me quiere decir que no importa qué contienente sea, el índice de democracia se mantiene en un promedio. No vale la pena medir la intensidad (asociación)
Si las variables son dependientes, calculo la intensidad. Para saber qué tan fuerte es la relación.
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).
Determinando tipo de relación: A partir del resumen estadístico se determina que es Numerica - Numérica Hipótesis: No hay correlación entre variables.
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)`
Todos son significativas
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 = "civilliber", 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
##
##
## $civilliber
##
## 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
Cuando el Pearson o Spearman son positivos, quiere decir que la relación es directa. Por lo tanto los puntos van del extremo inferior izquiero, al extremo superior derechos. (ASCENDENTE)
Si son negativos, van del extremo superior izquiero hasta el extremo inferior derecho. (DESCENDENTE)