El desafío de esta semana consiste en analizar datos del Reporte de Felicidad Mundial.
Para investigar en qué países las personas se sienten más felices se calcula la distribución del índice de felicidad por país.
En la siguiente tabla se puede observar:
Además, se presenta la desviación estándar del índice de felicidad promedio de cada país en una escala de colores, donde el color rojo alerta que la desviación estandar es alta y el color azul que la desviación estándar es pequeña.
library(formattable)
library(data.table)
#Levanto la base
felicidad <- readr::read_csv("https://raw.githubusercontent.com/cienciadedatos/datos-de-miercoles/master/datos/2019/2019-08-07/felicidad.csv")
colnames(felicidad)[1]<-"Pais"
colnames(felicidad)[2]<-"Anio"
colnames(felicidad)[3]<-"Indice_felicidad"
valores<-aggregate(felicidad$Indice_felicidad, by= list(felicidad$Pais), FUN= function(x) c(min(x), mean(x), max(x), sd(x)))
Indice_Felicidad<-as.data.table(round(valores$x,4))
Indice_Felicidad<-cbind(valores$Group.1, Indice_Felicidad)
colnames(Indice_Felicidad)<- c("Pais","Indice Minimo", "Indice Promedio", "Indice Maximo", "Desvio Estandar")
Indice_Felicidad<-Indice_Felicidad[order(Indice_Felicidad$`Indice Promedio`, decreasing = TRUE),]
PBI<-aggregate(felicidad$log_pib, by= list(felicidad$Pais), FUN= function(x) c(mean(x)))
PBI<-PBI$x
Indice_Felicidad$Log_PBI_Promedio<-PBI
Indice_Felicidad$Top_50_Promedio<-ifelse(Indice_Felicidad$`Indice Promedio`>5.9,TRUE,FALSE)
library(DT)
as.datatable(
formattable(Indice_Felicidad, list(
area(col=`Indice Minimo`)~normalize_bar(c("lightgray"),0.1),
area(col=`Indice Maximo`)~normalize_bar(c("lightgray"),0.1),
`Desvio Estandar`=color_tile("lightblue", "red"),
`Indice Promedio` = formatter("span",
style = x ~ style(color = ifelse(rank(-x) <= 50, "green", "gray")),
x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
Log_PBI_Promedio= formatter("span",
style = x ~ style(color = ifelse(rank(-x) <= 50, "green", "gray")),
x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
Top_50_Promedio = formatter("span",
style = x ~ style(color = ifelse(x,"green", "red")),
x ~ icontext(ifelse(x, "ok","remove"), ifelse(x, "Top 50", "Not Top 50")))
)))
El Top 3 de países más felices, de acuerdo al índice de felicidad promedio, está integrado por:
1º Dinamarca, 2º Finlandia y 3º Noruega.
Si se considera el Top 3 de acuerdo al mayor índice de felicidad obtenido, tenemos:
1º Dinamarca, 2º Finlandia y 3º Suiza.
Y si consideramos el Top 3 de países más felices de acuerdo al menor índice de felicidad obtenido, tenemos:
1º Dinamarca, 2º Suiza y 3º Noruega.
Para los países mencionados previamente dentro de los Top 3, se va a analizar la distribución del índice de felicidad a través de los años.
library(ggplot2)
grafico<-subset(felicidad[, c("Pais", "Anio", "Indice_felicidad")], felicidad$Pais%in%c("Suiza", "Noruega", "Finlandia", "Dinamarca"))%>%
ggplot(aes(x=Anio,y=Indice_felicidad, color=Pais))+
geom_line()+
geom_point()+
theme_minimal()+
labs(x = "Anio", y="Indice de Felicidad") +
theme( legend.position = "bottom", #leyenda abajo
legend.text = element_text(size = 8, colour = "black"), #leyenda en color
legend.title = element_text(face = "bold")) #titulo leyenda en negrita
grafico
Durante el período 2005-2011 se considera a Dinamarca el país “más feliz”, sin embargo en 2012 su índice de felicidad es superado por Noruega y Suiza.
En 2014 vuelve a obtener el primer puesto en felicidad junto con Suiza, cuyos índices de felicidad difieren en decimales.
Al año siguiente, nuevamente Noruega y Suiza vuelven a superar el índice de felicidad de Dinamarca.
En el año 2018 Finlandia se convierte en el país más feliz de ese año ya que su índice de felicidad supera en un 2.74% al índice de felicidad de Dinamarca.
ggplot(felicidad, aes(x=log_pib, y=Indice_felicidad)) + geom_point() +ylab("Indice de felicidad") + xlab("Log PBI") + geom_smooth(method=lm)+ theme_minimal()+ theme( legend.position = "bottom", #leyenda abajo
legend.text = element_text(size = 8, colour = "black"), #leyenda en color
legend.title = element_text(face = "bold")) #titulo leyenda en negrita
cor.test(~ felicidad$log_pib+felicidad$Indice_felicidad, method = "pearson")
##
## Pearson's product-moment correlation
##
## data: felicidad$log_pib and felicidad$Indice_felicidad
## t = 50.842, df = 1674, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## 0.7595144 0.7972074
## sample estimates:
## cor
## 0.7790639
Se observa que a medida que aumenta el log del PBI también aumenta el índice de felicidad. La correlación entre ambas variables es de 0.77 y la misma resulta significativa.
Se realiza el gráfico con la información de los 4 países más felices.
df_2<- as.data.frame(subset(felicidad, felicidad$Pais%in%c("Suiza", "Noruega", "Finlandia", "Dinamarca")))
ggplot(df_2, aes(x=log_pib, y=Indice_felicidad)) + geom_point() +ylab("Indice de felicidad") + xlab("Log PBI") + geom_smooth(method=lm)+ theme_minimal()+ theme( legend.position = "bottom", #leyenda abajo
legend.text = element_text(size = 8, colour = "black"), #leyenda en color
legend.title = element_text(face = "bold")) #titulo leyenda en negrita
cor.test(~ df_2$log_pib+df_2$Indice_felicidad, method = "pearson")
##
## Pearson's product-moment correlation
##
## data: df_2$log_pib and df_2$Indice_felicidad
## t = -0.87066, df = 38, p-value = 0.3894
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## -0.4325185 0.1794763
## sample estimates:
## cor
## -0.139852
Al calcular la correlación únicamente con los datos de los países que consideramos más felices no se obtienen resultados estadísticamente significativos.
Si observamos la distribución de los puntos discriminando por país, tenemos:
ggplot(df_2, aes(x=log_pib, y=Indice_felicidad, fill=Pais)) + geom_point() +ylab("Indice de felicidad") + xlab("Log PBI") + geom_smooth(method=lm)+ theme_minimal()+ theme( legend.position = "bottom", #leyenda abajo
legend.text = element_text(size = 8, colour = "black"), #leyenda en color
legend.title = element_text(face = "bold")) #titulo leyenda en negrita
mcfinal = felicidad[c(3:15)]
for (i in 1:ncol(mcfinal)) {
mcfinal<- mcfinal[!is.na(mcfinal[i]),]
}
Matriz_de_correlacion_FINAL = round(cor(mcfinal),4)
library(corrplot)
corrplot(Matriz_de_correlacion_FINAL,method="square", type= "upper")
Se observa que las variables más correlacionadas con el índice de felicidad son: log_pib, expectativa_vida, calidad_entrega, soporte_social y calidad_democracia.
A continuación se analiza cómo se percibe la democracia y la corrupción en los países considerados más felices.
ggplot(df_2, aes(x=percepcion_corrupcion, y=Indice_felicidad, fill=Pais)) + geom_point() +ylab("Indice de felicidad") + xlab("Percepci?n de corrupci?n") + geom_smooth(method=lm)+ theme_minimal()+ theme( legend.position = "bottom", #leyenda abajo
legend.text = element_text(size = 8, colour = "black"), #leyenda en color
legend.title = element_text(face = "bold")) #titulo leyenda en negrita
cor.test(~ df_2$percepcion_corrupcion+df_2$Indice_felicidad, method = "pearson")
##
## Pearson's product-moment correlation
##
## data: df_2$percepcion_corrupcion and df_2$Indice_felicidad
## t = -2.6087, df = 38, p-value = 0.01292
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## -0.62532092 -0.08902683
## sample estimates:
## cor
## -0.389728
ggplot(df_2, aes(x=calidad_democracia, y=Indice_felicidad, fill=Pais)) + geom_point() +ylab("Indice de felicidad") + xlab("Calidad de Democracia") + geom_smooth(method=lm)+ theme_minimal()+ theme( legend.position = "bottom", #leyenda abajo
legend.text = element_text(size = 8, colour = "black"), #leyenda en color
legend.title = element_text(face = "bold")) #titulo leyenda en negrita
cor.test(~ df_2$calidad_democracia+df_2$Indice_felicidad, method = "pearson")
##
## Pearson's product-moment correlation
##
## data: df_2$calidad_democracia and df_2$Indice_felicidad
## t = -1.0224, df = 34, p-value = 0.3138
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## -0.4743300 0.1652013
## sample estimates:
## cor
## -0.1727081