## 0 Configuración

# Configuración del documento
knitr::opts_chunk$set(echo = TRUE)

# Librerías esenciales
library(dplyr) # Libreria para la manipulacion de datos y encadena con pipes
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(data.table) # Para agrupamiento de un alto volumen de datos
## 
## Adjuntando el paquete: 'data.table'
## The following objects are masked from 'package:dplyr':
## 
##     between, first, last
library(readxl) #Libreria para leer excel
library(kableExtra) #librearia para crear tablas en formato html
## 
## Adjuntando el paquete: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(VIM) # libreria para analisis y manipulacion de valores NA.
## Cargando paquete requerido: colorspace
## Cargando paquete requerido: grid
## VIM is ready to use.
## Suggestions and bug-reports can be submitted at: https://github.com/statistikat/VIM/issues
## 
## Adjuntando el paquete: 'VIM'
## The following object is masked from 'package:datasets':
## 
##     sleep
library(corrplot) #Libreria para visualizar matrices de correlacion
## corrplot 0.95 loaded
library(ggplot2) # se requiere para poder visualizar
library(dplyr) #La usaremos para posibles trasformaciones
# 1.1 Diccionario de Datos
diccionario <- read_excel("Data Dictionary.xlsx")

# Creación de tablas, seleccionado las columnas de nuestro interes

tabla_variables <- select(diccionario, `Associated SDG GOAL`, Code, Description)

#Ordenamos el dataframe en orden ascendente por la columna ODS
tabla_variables <- arrange(tabla_variables, `Associated SDG GOAL`)


#Convertimos el dataframe en una tabla html y agregamos titulo
kable(tabla_variables, caption = "Variables y ODS asociados") %>% kable_styling()
Variables y ODS asociados
Associated SDG GOAL Code Description
Classification types Regime Regime classified considering the competitiveness of access to power as well as existence of liberal principles. Regime type is a weighted index that considers a variety of political metrics.
Classification types Income World Bank assigns the world’s economies to four income groups—low, lower-middle, upper-middle, and high-income countries.
Classification types Region World Region as classified by UN.
Classification types Continent Continent classification according to UN Convention
Economic General NE.EXP.GNFS.ZS Exports of goods and services represent the value of all goods and other market services provided to the rest of the world
Economic General NE.CON.TOTL.ZS Sum of household final consumption expenditure (private consumption) and general government final consumption expenditure (general government consumption).
Economic General NE.DAB.TOTL.ZS Sum of household final consumption expenditure (formerly private consumption), general government final consumption expenditure (formerly general government consumption), and gross capital formation (formerly gross domestic investment).
Economic General NY.GDP.MKTP.CD Current value (in USD) of total goods and services produced within a country.
Economic General NY.GNS.ICTR.ZS Calculated as gross national income less total consumption, plus net transfers
Economic General NE.CON.GOVT.ZS Final consumption expenditure (formerly general government consumption) includes all government current expenditures for purchases of goods and services (including compensation of employees). 
Economic General FP.CPI.TOTL.ZG Rate at which prices of goods and services brought by conusmers rise or fall. Estimated by using consumer price indices.
Economic General NE.IMP.GNFS.ZS Value of all goods and other market services received from the rest of the world
Economic General NE.TRD.GNFS.ZS Proportion of total GDP that is comprised by Trade activity.
Explanatory factors IT.NET.USER.ZS Individuals who have used the Internet (from any location) in the last 3 months
Explanatory factors GH.EM.IC.LUF NA
Explanatory factors SH.HIV.INCD.TL.P3 HIV rates per 1000 people
Explanatory factors IT.NET.USER.ZS % of countrys total population that has access to working internet
Explanatory factors SP.DYN.LE00.IN Average life expectancy for newborn babies
Explanatory factors SP.POP.TOTL Total population
Explanatory factors NY.GDP.TOTL.RT.ZS % Income accrued from natural resources (e.g. Exports) as a percentage of GDP
Explanatory factors SP.URB.TOTL.IN.ZS What proportion of total population live in urban areas?
Explanatory factors SP.RUR.TOTL.ZS Percentage of a countries total population that occupy rural areas.
Goal 1. End poverty in all its forms everywhere SP_ACS_BSRVH2O Percentage of the population who have sustained access to basic water drinking services.
Goal 1. End poverty in all its forms everywhere SI_POV_DAY1 Percentage of the population living on less than $1.90 a day at 2011 international prices. The international poverty line is currently set at $1.90 a day at 2011 international prices.
Goal 10. Reduce inequality within and among countries SI.POV.GINI Score awarded based on how equitably income is dispersed within a country
Goal 10. Reduce inequality within and among countries NY.ADJ.NNTY.PC.KD.ZG Percentage yearly growth of adjusted net national income divided by number of people in country
Goal 13. Take urgent action to combat climate change and its impacts NY.ADJ.SVNX.GN.ZS Measure that monitors whether savings and investment in a country compensate for depreciation of natural and physical capital
Goal 13. Take urgent action to combat climate change and its impacts NY.ADJ.DCO2.GN.ZS Measure that monitors whether savings and investment in a country compensate for depreciation of natural and physical capital
Goal 13. Take urgent action to combat climate change and its impacts NY.ADJ.DRES.GN.ZS Measure that monitors whether savings and investment in a country compensate for depreciation of natural and physical capital
Goal 13. Take urgent action to combat climate change and its impacts NY.ADJ.DPEM.GN.ZS Measure that monitors whether savings and investment in a country compensate for depreciation of natural and physical capital
Goal 13. Take urgent action to combat climate change and its impacts NY.ADJ.DFOR.GN.ZS Measure, calculated as the product of unit resource rents and the excess of roundwood harvest over natural growth.
Goal 2. End hunger, achieve food security and improved nutrition and promote sustainable agriculture SN_ITK_DEFC Percentage of the population whose habitual food consumption is insufficient to provide the dietary energy levels that are required to maintain a normal active and healthy life. 
Goal 3. Ensure healthy lives and promote well-being for all at all ages SP.DYN.LE00.IN Value which captures the expectated age a newborn baby will live to
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.PRM.UNER.ZS Percentage of primary-school-age children who are not enrolled in primary or secondary school. Children in the official primary age group that are in preprimary education should be considered out of school.
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.COM.DURS Duration of compulsory education is the number of years that children are legally obliged to attend school.
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.PRM.CMPT.ZS Number of new entrants (enrollments minus repeaters) in the last grade of primary education, regardless of age, divided by the population at the entrance age for the last grade of primary education.
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.PRE.ENRR Ratio of total enrollment, regardless of age, to the population of the age group that officially corresponds to the level of education shown
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.PRM.ENRR Ratio of total enrollment, regardless of age, to the population of the age group that officially corresponds to the level of education shown
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.SEC.ENRR Ratio of total enrollment, regardless of age, to the population of the age group that officially corresponds to the level of education shown
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.SEC.ENRR.FE Ratio of female enrollment, regardless of age, to the population of the age group that officially corresponds to the level of education shown
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all SE.PRM.ENRL.TC.ZS Average number of pupils per teacher in primary school.
Goal 5. Achieve gender equality and empower all women and girls SG.GEN.PARL.ZS Percentage of parliamentary seats in a single or lower chamber held by women.
Goal 5. Achieve gender equality and empower all women and girls SG.LAW.INDX index measures how laws and regulations affect women’s economic opportunity. Overall scores are calculated by taking the average score of each of the eight areas (Going Places, Starting a Job, Getting Paid, Getting Married, Having Children, Running a Business, Managing Assets and Getting a Pension), with 100 representing the highest possible score.
Goal 7. Ensure access to affordable, reliable, sustainable and modern energy for all EG.FEC.RNEW.ZS Share of renewables energy in total final energy consumption.
Goal 7. Ensure access to affordable, reliable, sustainable and modern energy for all EG.ELC.RNEW.ZS Share of electrity generated by renewable power plants in total electricity generated by all types of plants.
Goal 8. Promote sustained, inclusive and sustainable economic growth, full and productive employment and decent work for all SL_TLF_UEM Share of labour force without work but available and seeking employment (male)
Goal 8. Promote sustained, inclusive and sustainable economic growth, full and productive employment and decent work for all SL_TLF_UEM Share of labour force without work but available and seeking employment (female)
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation IT_MOB_2GNTWK Percentage of inhabitants living within range of a mobile-cellular signal, irrespective of whether or not they are mobile phone subscribers or users.
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation IT_MOB_3GNTWK Percentage of inhabitants living within range of a mobile-cellular signal, irrespective of whether or not they are mobile phone subscribers or users. 
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation EG.ELC.ACCS.ZS Percentage of population with access to electricity. Electrification data are collected from industry, national surveys and international sources.
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation FB.ATM.TOTL.P5 Number of physical ATMs that allow clients to make financial transactions in a public place.
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation IC.REG.COST.PC.FE.ZS Cost to register a business is normalized by presenting it as a percentage of the gross national income (GNI) per capita.
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation IC.REG.COST.PC.MA.ZS Cost to register a business is normalized by presenting it as a percentage of the gross national income (GNI) per capita.
#Creamos la segunda tabla con listados unicos, de la columna ODS, eliminando duplicados y ordenamos la lista.
tabla_ods <- select(diccionario, `Associated SDG GOAL`)
tabla_ods <- distinct(tabla_ods)
tabla_ods <- arrange(tabla_ods, `Associated SDG GOAL`)

# creamos y formateamos la tabla "Listados de ODS"
kable(tabla_ods, caption = "Listado de ODS") %>% kable_styling()
Listado de ODS
Associated SDG GOAL
Classification types
Economic General
Explanatory factors
Goal 1. End poverty in all its forms everywhere
Goal 10. Reduce inequality within and among countries
Goal 13. Take urgent action to combat climate change and its impacts
Goal 2. End hunger, achieve food security and improved nutrition and promote sustainable agriculture
Goal 3. Ensure healthy lives and promote well-being for all at all ages
Goal 4. Ensure inclusive and equitable quality education and promoted lifelong learning oppurtunities for all
Goal 5. Achieve gender equality and empower all women and girls
Goal 7. Ensure access to affordable, reliable, sustainable and modern energy for all
Goal 8. Promote sustained, inclusive and sustainable economic growth, full and productive employment and decent work for all
Goal 9. Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation
## 1.2 Fichero de Datos

#cargamos los datos desde el csv
datos <- read.csv("WorldSustainabilityDataset.csv") 

# Renombramos las columnas indicadas en la PEC1
names(datos)[names(datos) == "Country.Name"] <- "Country"
names(datos)[names(datos) == "Country.Code"] <- "CountryCode"
names(datos)[names(datos) == "Income.Classification.World.Bank.Definition"] <- "Income"
names(datos)[names(datos) == "Regime.Type.RoW.MeasureDefinition."] <- "Regime"
names(datos)[names(datos) == "World.Regions..UN.SDG.Definition."] <- "Region"

#Mostramos los nuevos nombres de las columnas
names(datos)
##  [1] "Country"                                                                                            
##  [2] "CountryCode"                                                                                        
##  [3] "Year"                                                                                               
##  [4] "Access.to.electricity....of.population....EG.ELC.ACCS.ZS"                                           
##  [5] "Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG"                   
##  [6] "Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS"         
##  [7] "Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS"                             
##  [8] "Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS"                       
##  [9] "Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS"                              
## [10] "Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS"                       
## [11] "Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5"                             
## [12] "Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS"                                                         
## [13] "Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS"                                  
## [14] "Compulsory.education..duration..years....SE.COM.DURS"                                               
## [15] "Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS"          
## [16] "Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS"            
## [17] "Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS"                                          
## [18] "Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS"                                          
## [19] "GDP..current.US.....NY.GDP.MKTP.CD"                                                                 
## [20] "GDP.per.capita..current.US.....NY.GDP.PCAP.CD"                                                      
## [21] "General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS"                       
## [22] "Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS"                                             
## [23] "Gross.savings....of.GDP....NY.GNS.ICTR.ZS"                                                          
## [24] "Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS"                                          
## [25] "Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG"                                             
## [26] "Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS"                          
## [27] "Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS"                     
## [28] "Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS"                                                   
## [29] "Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS"                      
## [30] "Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS"                
## [31] "School.enrollment..preprimary....gross....SE.PRE.ENRR"                                              
## [32] "School.enrollment..primary....gross....SE.PRM.ENRR"                                                 
## [33] "School.enrollment..secondary....gross....SE.SEC.ENRR"                                               
## [34] "Trade....of.GDP....NE.TRD.GNFS.ZS"                                                                  
## [35] "Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX"                                 
## [36] "Prevalence.of.undernourishment.......SN_ITK_DEFC"                                                   
## [37] "Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1"                        
## [38] "Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK"               
## [39] "Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK"               
## [40] "Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O"                  
## [41] "Unemployment.rate..male.......SL_TLF_UEM"                                                           
## [42] "Unemployment.rate..women.......SL_TLF_UEM"                                                          
## [43] "Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF"
## [44] "Continent"                                                                                          
## [45] "Gini.index..World.Bank.estimate....SI.POV.GINI"                                                     
## [46] "Income.Classification..World.Bank.Definition."                                                      
## [47] "Individuals.using.the.Internet....of.population....IT.NET.USER.ZS"                                  
## [48] "Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN"                                           
## [49] "Population..total...SP.POP.TOTL"                                                                    
## [50] "Regime.Type..RoW.Measure.Definition."                                                               
## [51] "Rural.population....of.total.population....SP.RUR.TOTL.ZS"                                          
## [52] "Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS"                                       
## [53] "Urban.population....of.total.population....SP.URB.TOTL.IN.ZS"                                       
## [54] "Region"
# 2 Tipos de datos y sus posibles valores erroneos, vacios y de otro tipo

# Reemplazar valores vacíos por NA y convertir a factor

# Rellenar campos vacios con NA en columnas de texto
datos[sapply(datos, is.character)] <- lapply(datos[sapply(datos, is.character)], function(x) na_if(x, ""))

# Convertir a variables factor, todas las columnas indicadas
datos$Country.Name <- as.factor(datos$Country)
datos$CountryCode <- as.factor(datos$CountryCode)
datos$Regime <- as.factor(datos$Regime)
datos$Income <- as.factor(datos$Income)
datos$Region <- as.factor(datos$Region)
datos$Continent <- as.factor(datos$Continent)

#Mostramos la estructura de los datos
str(datos)
## 'data.frame':    3287 obs. of  57 variables:
##  $ Country                                                                                            : chr  "Aruba" "Aruba" "Aruba" "Aruba" ...
##  $ CountryCode                                                                                        : Factor w/ 173 levels "ABW","AGO","ALB",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ Year                                                                                               : int  2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 ...
##  $ Access.to.electricity....of.population....EG.ELC.ACCS.ZS                                           : num  91.7 100 100 100 100 ...
##  $ Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG                   : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS         : num  15.39 11.49 3.89 6.71 9.8 ...
##  $ Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS                             : num  2.39 2.51 2.72 2.73 2.68 ...
##  $ Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS                       : num  0.00019 0.000214 0.000223 0.000243 0.000256 ...
##  $ Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS                              : num  0.00019 0.000214 0.000223 0.000243 0.000256 ...
##  $ Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS                       : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5                             : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS                                                         : num  51.8 53.6 58.5 61.2 57.3 ...
##  $ Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS                                  : num  1.603 0.323 1.816 3.322 2.177 ...
##  $ Compulsory.education..duration..years....SE.COM.DURS                                               : int  NA NA NA NA NA NA NA NA NA NA ...
##  $ Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS          : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS            : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS                                          : num  74.4 70.5 64.9 63.1 65.1 ...
##  $ Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS                                          : num  70.8 74.3 77.6 78.6 74.7 ...
##  $ GDP..current.US.....NY.GDP.MKTP.CD                                                                 : num  1.87e+09 1.92e+09 1.94e+09 2.02e+09 2.23e+09 ...
##  $ GDP.per.capita..current.US.....NY.GDP.PCAP.CD                                                      : num  20618 20670 20437 20834 22568 ...
##  $ General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS                       : num  21.4 24.5 25.2 24.7 23.2 ...
##  $ Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS                                             : num  96.3 98.1 104.5 107.8 103.5 ...
##  $ Gross.savings....of.GDP....NY.GNS.ICTR.ZS                                                          : num  23.7 19.3 12 14.5 17.1 ...
##  $ Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS                                          : num  70.7 68.5 69.4 70.9 68.6 ...
##  $ Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG                                             : num  4.04 2.88 3.32 3.66 2.53 ...
##  $ Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS                          : num  97.1 94.4 94.8 90.2 90.6 ...
##  $ Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS                     : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS                                                   : num  19.1 18.9 19.1 18.4 18.5 ...
##  $ Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS                      : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS                : num  0.175 0.181 0.181 0.185 0.187 ...
##  $ School.enrollment..preprimary....gross....SE.PRE.ENRR                                              : num  95.9 97.6 98.4 99.6 98.7 ...
##  $ School.enrollment..primary....gross....SE.PRM.ENRR                                                 : num  111 109 111 109 111 ...
##  $ School.enrollment..secondary....gross....SE.SEC.ENRR                                               : num  96.5 98 100.5 99.1 97.3 ...
##  $ Trade....of.GDP....NE.TRD.GNFS.ZS                                                                  : num  145 139 134 134 134 ...
##  $ Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX                                 : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Prevalence.of.undernourishment.......SN_ITK_DEFC                                                   : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1                        : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK               : num  NA NA NA NA NA 90 99 99 99 NA ...
##  $ Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK               : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O                  : int  NA NA NA NA NA NA NA NA NA NA ...
##  $ Unemployment.rate..male.......SL_TLF_UEM                                                           : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Unemployment.rate..women.......SL_TLF_UEM                                                          : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF: num  2.38 2.41 2.44 2.56 2.62 ...
##  $ Continent                                                                                          : Factor w/ 6 levels "Africa","Asia",..: 4 4 4 4 4 4 4 4 4 4 ...
##  $ Gini.index..World.Bank.estimate....SI.POV.GINI                                                     : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Income.Classification..World.Bank.Definition.                                                      : chr  "High income" "High income" "High income" "High income" ...
##  $ Individuals.using.the.Internet....of.population....IT.NET.USER.ZS                                  : num  NA 17.1 18.8 20.8 23 25.4 28 30.9 52 58 ...
##  $ Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN                                           : num  NA 73.9 73.9 74 74.2 ...
##  $ Population..total...SP.POP.TOTL                                                                    : int  NA 92892 94992 97016 98744 100028 100830 101226 101362 101452 ...
##  $ Regime.Type..RoW.Measure.Definition.                                                               : chr  NA NA NA NA ...
##  $ Rural.population....of.total.population....SP.RUR.TOTL.ZS                                          : num  53.3 53.7 54 54.4 54.8 ...
##  $ Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS                                       : num  NA 0.000712 0.000657 0.0007 0.000685 ...
##  $ Urban.population....of.total.population....SP.URB.TOTL.IN.ZS                                       : num  NA 46.3 46 45.6 45.2 ...
##  $ Region                                                                                             : Factor w/ 7 levels "Central and Southern Asia",..: 4 4 4 4 4 4 4 4 4 4 ...
##  $ Country.Name                                                                                       : Factor w/ 173 levels "Albania","Algeria",..: 7 7 7 7 7 7 7 7 7 7 ...
##  $ Regime                                                                                             : Factor w/ 4 levels "Closed Autocracy",..: NA NA NA NA NA NA NA NA NA NA ...
##  $ Income                                                                                             : Factor w/ 4 levels "High income",..: 1 1 1 1 1 1 1 1 1 1 ...
#mostramos tipos de datos e informacion basica de analisis
summary(datos$Income)
##         High income          Low income Lower-middle income Upper-middle income 
##                 899                 753                 868                 765 
##                NA's 
##                   2
# 2. TIPOS DE DATOS Y POSIBLES INCONSISTENCIAS

cat("INICIO DEL ANÁLISIS DE CALIDAD DE LOS DATOS\n")
## INICIO DEL ANÁLISIS DE CALIDAD DE LOS DATOS
# Verificación inicial del estado del dataset
cat("Dimensión del dataset y estructura inicial", dim(datos), "= ")
## Dimensión del dataset y estructura inicial 3287 57 =
str(datos)
## 'data.frame':    3287 obs. of  57 variables:
##  $ Country                                                                                            : chr  "Aruba" "Aruba" "Aruba" "Aruba" ...
##  $ CountryCode                                                                                        : Factor w/ 173 levels "ABW","AGO","ALB",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ Year                                                                                               : int  2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 ...
##  $ Access.to.electricity....of.population....EG.ELC.ACCS.ZS                                           : num  91.7 100 100 100 100 ...
##  $ Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG                   : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS         : num  15.39 11.49 3.89 6.71 9.8 ...
##  $ Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS                             : num  2.39 2.51 2.72 2.73 2.68 ...
##  $ Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS                       : num  0.00019 0.000214 0.000223 0.000243 0.000256 ...
##  $ Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS                              : num  0.00019 0.000214 0.000223 0.000243 0.000256 ...
##  $ Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS                       : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5                             : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS                                                         : num  51.8 53.6 58.5 61.2 57.3 ...
##  $ Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS                                  : num  1.603 0.323 1.816 3.322 2.177 ...
##  $ Compulsory.education..duration..years....SE.COM.DURS                                               : int  NA NA NA NA NA NA NA NA NA NA ...
##  $ Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS          : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS            : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS                                          : num  74.4 70.5 64.9 63.1 65.1 ...
##  $ Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS                                          : num  70.8 74.3 77.6 78.6 74.7 ...
##  $ GDP..current.US.....NY.GDP.MKTP.CD                                                                 : num  1.87e+09 1.92e+09 1.94e+09 2.02e+09 2.23e+09 ...
##  $ GDP.per.capita..current.US.....NY.GDP.PCAP.CD                                                      : num  20618 20670 20437 20834 22568 ...
##  $ General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS                       : num  21.4 24.5 25.2 24.7 23.2 ...
##  $ Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS                                             : num  96.3 98.1 104.5 107.8 103.5 ...
##  $ Gross.savings....of.GDP....NY.GNS.ICTR.ZS                                                          : num  23.7 19.3 12 14.5 17.1 ...
##  $ Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS                                          : num  70.7 68.5 69.4 70.9 68.6 ...
##  $ Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG                                             : num  4.04 2.88 3.32 3.66 2.53 ...
##  $ Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS                          : num  97.1 94.4 94.8 90.2 90.6 ...
##  $ Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS                     : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS                                                   : num  19.1 18.9 19.1 18.4 18.5 ...
##  $ Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS                      : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS                : num  0.175 0.181 0.181 0.185 0.187 ...
##  $ School.enrollment..preprimary....gross....SE.PRE.ENRR                                              : num  95.9 97.6 98.4 99.6 98.7 ...
##  $ School.enrollment..primary....gross....SE.PRM.ENRR                                                 : num  111 109 111 109 111 ...
##  $ School.enrollment..secondary....gross....SE.SEC.ENRR                                               : num  96.5 98 100.5 99.1 97.3 ...
##  $ Trade....of.GDP....NE.TRD.GNFS.ZS                                                                  : num  145 139 134 134 134 ...
##  $ Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX                                 : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Prevalence.of.undernourishment.......SN_ITK_DEFC                                                   : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1                        : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK               : num  NA NA NA NA NA 90 99 99 99 NA ...
##  $ Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK               : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O                  : int  NA NA NA NA NA NA NA NA NA NA ...
##  $ Unemployment.rate..male.......SL_TLF_UEM                                                           : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Unemployment.rate..women.......SL_TLF_UEM                                                          : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF: num  2.38 2.41 2.44 2.56 2.62 ...
##  $ Continent                                                                                          : Factor w/ 6 levels "Africa","Asia",..: 4 4 4 4 4 4 4 4 4 4 ...
##  $ Gini.index..World.Bank.estimate....SI.POV.GINI                                                     : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ Income.Classification..World.Bank.Definition.                                                      : chr  "High income" "High income" "High income" "High income" ...
##  $ Individuals.using.the.Internet....of.population....IT.NET.USER.ZS                                  : num  NA 17.1 18.8 20.8 23 25.4 28 30.9 52 58 ...
##  $ Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN                                           : num  NA 73.9 73.9 74 74.2 ...
##  $ Population..total...SP.POP.TOTL                                                                    : int  NA 92892 94992 97016 98744 100028 100830 101226 101362 101452 ...
##  $ Regime.Type..RoW.Measure.Definition.                                                               : chr  NA NA NA NA ...
##  $ Rural.population....of.total.population....SP.RUR.TOTL.ZS                                          : num  53.3 53.7 54 54.4 54.8 ...
##  $ Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS                                       : num  NA 0.000712 0.000657 0.0007 0.000685 ...
##  $ Urban.population....of.total.population....SP.URB.TOTL.IN.ZS                                       : num  NA 46.3 46 45.6 45.2 ...
##  $ Region                                                                                             : Factor w/ 7 levels "Central and Southern Asia",..: 4 4 4 4 4 4 4 4 4 4 ...
##  $ Country.Name                                                                                       : Factor w/ 173 levels "Albania","Algeria",..: 7 7 7 7 7 7 7 7 7 7 ...
##  $ Regime                                                                                             : Factor w/ 4 levels "Closed Autocracy",..: NA NA NA NA NA NA NA NA NA NA ...
##  $ Income                                                                                             : Factor w/ 4 levels "High income",..: 1 1 1 1 1 1 1 1 1 1 ...
# 2.1 VARIABLES CUANTITATIVAS

cat("\n2.1 ANÁLISIS DE VARIABLES CUANTITATIVAS\n")
## 
## 2.1 ANÁLISIS DE VARIABLES CUANTITATIVAS
# Obtener el número total de filas
total_observaciones <- nrow(datos)
cat("TOTAL DE OBSERVACIONES (Filas en el Dataset):", total_observaciones, "\n")
## TOTAL DE OBSERVACIONES (Filas en el Dataset): 3287
# -------------------------------------------------------------

# Identificar variables cuantitativas o numericas
variables_cuantitativas <- names(datos)[sapply(datos, is.numeric)]
cat("Variables cuantitativas identificadas:", length(variables_cuantitativas), "\n")
## Variables cuantitativas identificadas: 48
#Imprimimos un listado de las variables con la funcion paste.
cat("Lista:", paste(variables_cuantitativas, collapse = ", "), "\n")
## Lista: Year, Access.to.electricity....of.population....EG.ELC.ACCS.ZS, Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG, Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS, Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS, Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS, Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS, Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS, Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5, Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS, Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS, Compulsory.education..duration..years....SE.COM.DURS, Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS, Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS, Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS, Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS, GDP..current.US.....NY.GDP.MKTP.CD, GDP.per.capita..current.US.....NY.GDP.PCAP.CD, General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS, Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS, Gross.savings....of.GDP....NY.GNS.ICTR.ZS, Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS, Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG, Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS, Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS, Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS, Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS, Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS, School.enrollment..preprimary....gross....SE.PRE.ENRR, School.enrollment..primary....gross....SE.PRM.ENRR, School.enrollment..secondary....gross....SE.SEC.ENRR, Trade....of.GDP....NE.TRD.GNFS.ZS, Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX, Prevalence.of.undernourishment.......SN_ITK_DEFC, Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1, Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK, Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK, Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O, Unemployment.rate..male.......SL_TLF_UEM, Unemployment.rate..women.......SL_TLF_UEM, Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF, Gini.index..World.Bank.estimate....SI.POV.GINI, Individuals.using.the.Internet....of.population....IT.NET.USER.ZS, Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN, Population..total...SP.POP.TOTL, Rural.population....of.total.population....SP.RUR.TOTL.ZS, Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS, Urban.population....of.total.population....SP.URB.TOTL.IN.ZS
# Análisis de cada variable cuantitativa individualmente
for (var in variables_cuantitativas) {
  cat("\n Análisis de", var, "\n")
  cat("Tipo de dato:", class(datos[[var]]), "\n")
  
  # Total de NA y CÁLCULO DEL PORCENTAJE
  num_na <- sum(is.na(datos[[var]]))
  porc_na <- round((num_na / total_observaciones) * 100, 2)
  
  # Calculo total de valores sin errores visibles y su procentaje
  num_completos <- total_observaciones - num_na
  porc_completos <- 100 - porc_na
  
  cat("Valores Completos:", "num_completos", " (", round(porc_completos, 2), "%)\n")
  cat("Valores NA:", num_na, " (", porc_na, "%)\n")
  
  cat("Resumen estadístico:\n")
  print(summary(datos[[var]]))
  
  # Detección de posibles valores extremos o erróneos
  valores_unicos <- unique(datos[[var]])
  cat("Valores únicos:", length(valores_unicos), "\n")
  
  # Verificar si hay valores infinitos
  if (any(is.infinite(datos[[var]]))) {
    cat("Valores infinitos encontrados en", var, "\n")
  }
  
  # Verificar si hay valores negativos donde no debería haberlos usando la funcion !grep
  if (any(datos[[var]] < 0, na.rm = TRUE) && 
      !grepl("change|difference|growth", var, ignore.case = TRUE)) {
    cat("Valores negativos en", var, "- Revisar consistencia\n")
  }
}
## 
##  Análisis de Year 
## Tipo de dato: integer 
## Valores Completos: num_completos  ( 100 %)
## Valores NA: 0  ( 0 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    2000    2004    2009    2009    2014    2018 
## Valores únicos: 19 
## 
##  Análisis de Access.to.electricity....of.population....EG.ELC.ACCS.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 97.14 %)
## Valores NA: 94  ( 2.86 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    1.27   62.90   98.65   79.30  100.00  100.00      94 
## Valores únicos: 1736 
## 
##  Análisis de Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 78.07 %)
## Valores NA: 721  ( 21.93 %)
## Resumen estadístico:
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's 
## -645.6553   -0.2468    2.5454    2.4999    5.5458  229.4931       721 
## Valores únicos: 2567 
## 
##  Análisis de Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 79.95 %)
## Valores NA: 659  ( 20.05 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
## -97.525   3.339   8.753   8.870  15.291  45.354     659 
## Valores únicos: 2629 
## Valores negativos en Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS - Revisar consistencia
## 
##  Análisis de Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 97.96 %)
## Valores NA: 67  ( 2.04 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##  0.09029  0.74131  1.14587  1.74267  2.05693 27.10147       67 
## Valores únicos: 3221 
## 
##  Análisis de Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.13 %)
## Valores NA: 193  ( 5.87 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##  0.00000  0.07854  0.87874  3.81205  4.65670 71.29076      193 
## Valores únicos: 2810 
## 
##  Análisis de Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.65 %)
## Valores NA: 176  ( 5.35 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##  0.00000  0.00000  0.00000  0.69283  0.09704 40.77257      176 
## Valores únicos: 1050 
## 
##  Análisis de Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.28 %)
## Valores NA: 188  ( 5.72 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##  0.0095  0.1496  0.3887  0.8805  1.2861  6.5429     188 
## Valores únicos: 2938 
## 
##  Análisis de Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 69.52 %)
## Valores NA: 1002  ( 30.48 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.000   9.559  34.952  45.392  62.252 324.172    1002 
## Valores únicos: 2275 
## 
##  Análisis de Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 84.48 %)
## Valores NA: 510  ( 15.52 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   2.857  27.223  47.054  57.034  72.466 396.186     510 
## Valores únicos: 2778 
## 
##  Análisis de Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 67.69 %)
## Valores NA: 1062  ( 32.31 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##  0.0000  0.7702  2.9721  7.5794  9.1173 73.1046    1062 
## Valores únicos: 2206 
## 
##  Análisis de Compulsory.education..duration..years....SE.COM.DURS 
## Tipo de dato: integer 
## Valores Completos: num_completos  ( 90.63 %)
## Valores NA: 308  ( 9.37 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    4.00    8.00    9.00    9.33   10.00   17.00     308 
## Valores únicos: 15 
## 
##  Análisis de Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 76.09 %)
## Valores NA: 786  ( 23.91 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00    4.80   14.60   48.16   45.60 1540.20     786 
## Valores únicos: 928 
## 
##  Análisis de Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 76.09 %)
## Valores NA: 786  ( 23.91 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00    4.80   14.60   48.16   45.60 1540.20     786 
## Valores únicos: 925 
## 
##  Análisis de Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.86 %)
## Valores NA: 169  ( 5.14 %)
## Resumen estadístico:
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's 
##   0.09946  23.94541  35.56111  42.15827  52.36370 228.99377       169 
## Valores únicos: 3119 
## 
##  Análisis de Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 92.7 %)
## Valores NA: 240  ( 7.3 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   16.71   71.26   79.51   80.41   89.75  241.97     240 
## Valores únicos: 3048 
## 
##  Análisis de GDP..current.US.....NY.GDP.MKTP.CD 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 98.75 %)
## Valores NA: 41  ( 1.25 %)
## Resumen estadístico:
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's 
## 1.811e+08 6.550e+09 2.498e+10 3.508e+11 1.760e+11 2.061e+13        41 
## Valores únicos: 3244 
## 
##  Análisis de GDP.per.capita..current.US.....NY.GDP.PCAP.CD 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 98.75 %)
## Valores NA: 41  ( 1.25 %)
## Resumen estadístico:
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's 
##     90.53   1270.32   4335.71  12305.69  15354.66 118823.65        41 
## Valores únicos: 3247 
## 
##  Análisis de General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 92.21 %)
## Valores NA: 256  ( 7.79 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##   0.9517  11.6790  15.7547  16.3328  19.2780 147.7333      256 
## Valores únicos: 3032 
## 
##  Análisis de Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 92.7 %)
## Valores NA: 240  ( 7.3 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   40.11   96.52  102.84  104.53  112.28  264.78     240 
## Valores únicos: 3048 
## 
##  Análisis de Gross.savings....of.GDP....NY.GNS.ICTR.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 84.39 %)
## Valores NA: 513  ( 15.61 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##  -70.26   15.26   21.16   22.72   28.08  372.99     513 
## Valores únicos: 2775 
## Valores negativos en Gross.savings....of.GDP....NY.GNS.ICTR.ZS - Revisar consistencia
## 
##  Análisis de Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.86 %)
## Valores NA: 169  ( 5.14 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##   0.0647  29.0604  40.2742  47.0147  58.7495 236.3910      169 
## Valores únicos: 3119 
## 
##  Análisis de Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 93.79 %)
## Valores NA: 204  ( 6.21 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
## -18.109   1.621   3.467   5.903   6.827 513.907     204 
## Valores únicos: 3083 
## Valores negativos en Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG - Revisar consistencia
## 
##  Análisis de Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 67.72 %)
## Valores NA: 1061  ( 32.28 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   16.58   83.24   95.62   88.73  100.05  134.54    1061 
## Valores únicos: 2226 
## 
##  Análisis de Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 93.15 %)
## Valores NA: 225  ( 6.85 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.000   9.821  16.000  17.977  24.468  63.750     225 
## Valores únicos: 904 
## 
##  Análisis de Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 71.98 %)
## Valores NA: 921  ( 28.02 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   8.141  15.279  21.088  25.250  32.018 100.236     921 
## Valores únicos: 2365 
## 
##  Análisis de Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 84.3 %)
## Valores NA: 516  ( 15.7 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.000   1.892  17.864  32.362  57.710 100.000     516 
## Valores únicos: 2267 
## 
##  Análisis de Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 100 %)
## Valores NA: 0  ( 0 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   0.000   6.835  22.660  32.673  54.638  98.343 
## Valores únicos: 3176 
## 
##  Análisis de School.enrollment..preprimary....gross....SE.PRE.ENRR 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 71.46 %)
## Valores NA: 938  ( 28.54 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##   0.7419  29.8123  62.3437  59.1082  87.2502 166.9931      938 
## Valores únicos: 2350 
## 
##  Análisis de School.enrollment..primary....gross....SE.PRM.ENRR 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 84.67 %)
## Valores NA: 504  ( 15.33 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   32.36   98.82  102.74  103.49  109.30  150.79     504 
## Valores únicos: 2783 
## 
##  Análisis de School.enrollment..secondary....gross....SE.SEC.ENRR 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 73.93 %)
## Valores NA: 857  ( 26.07 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   6.197  64.530  88.407  81.127 100.200 163.935     857 
## Valores únicos: 2431 
## 
##  Análisis de Trade....of.GDP....NE.TRD.GNFS.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.86 %)
## Valores NA: 169  ( 5.14 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##   0.1674  55.4193  79.2857  89.1730 107.4491 442.6200      169 
## Valores únicos: 3119 
## 
##  Análisis de Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 97.69 %)
## Valores NA: 76  ( 2.31 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   23.75   58.75   71.88   69.56   82.50  100.00      76 
## Valores únicos: 107 
## 
##  Análisis de Prevalence.of.undernourishment.......SN_ITK_DEFC 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 55.8 %)
## Valores NA: 1453  ( 44.2 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##     2.5     5.7    10.4    14.5    20.2    67.5    1453 
## Valores únicos: 400 
## 
##  Análisis de Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 39.67 %)
## Valores NA: 1983  ( 60.33 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.000   0.200   1.000   7.484   6.525  94.300    1983 
## Valores únicos: 286 
## 
##  Análisis de Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 71.46 %)
## Valores NA: 938  ( 28.54 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00   90.00   98.80   89.51   99.80  100.00     938 
## Valores únicos: 373 
## 
##  Análisis de Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 41.28 %)
## Valores NA: 1930  ( 58.72 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00   56.63   90.00   74.18   98.40  100.00    1930 
## Valores únicos: 404 
## 
##  Análisis de Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O 
## Tipo de dato: integer 
## Valores Completos: num_completos  ( 55.89 %)
## Valores NA: 1450  ( 44.11 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   26.00   91.00   97.00   92.92  100.00  100.00    1450 
## Valores únicos: 67 
## 
##  Análisis de Unemployment.rate..male.......SL_TLF_UEM 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 54.97 %)
## Valores NA: 1480  ( 45.03 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.100   4.100   6.400   7.987  10.000  37.000    1480 
## Valores únicos: 260 
## 
##  Análisis de Unemployment.rate..women.......SL_TLF_UEM 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 54.94 %)
## Valores NA: 1481  ( 45.06 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.200   4.725   7.500   9.811  12.800  42.800    1481 
## Valores únicos: 302 
## 
##  Análisis de Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 99.94 %)
## Valores NA: 2  ( 0.06 %)
## Resumen estadístico:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##    0.048    2.426   12.621  174.647   72.012 9956.569        2 
## Valores únicos: 2979 
## 
##  Análisis de Gini.index..World.Bank.estimate....SI.POV.GINI 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 39.64 %)
## Valores NA: 1984  ( 60.36 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   23.70   30.90   35.60   37.51   42.80   64.80    1984 
## Valores únicos: 332 
## 
##  Análisis de Individuals.using.the.Internet....of.population....IT.NET.USER.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 90.84 %)
## Valores NA: 301  ( 9.16 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00    6.00   25.00   33.12   58.00   99.65     301 
## Valores únicos: 2448 
## 
##  Análisis de Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.19 %)
## Valores NA: 191  ( 5.81 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   40.37   65.11   72.56   70.16   76.57   84.93     191 
## Valores únicos: 2926 
## 
##  Análisis de Population..total...SP.POP.TOTL 
## Tipo de dato: integer 
## Valores Completos: num_completos  ( 94.49 %)
## Valores NA: 181  ( 5.51 %)
## Resumen estadístico:
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's 
## 6.967e+04 2.407e+06 8.368e+06 3.892e+07 2.605e+07 1.393e+09       181 
## Valores únicos: 3106 
## 
##  Análisis de Rural.population....of.total.population....SP.RUR.TOTL.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 99.73 %)
## Valores NA: 9  ( 0.27 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00   24.82   42.65   42.89   60.73   91.75       9 
## Valores únicos: 3138 
## 
##  Análisis de Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 92.88 %)
## Valores NA: 234  ( 7.12 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##  0.0000  0.3859  2.1220  7.0159  8.8783 81.9500     234 
## Valores únicos: 2989 
## 
##  Análisis de Urban.population....of.total.population....SP.URB.TOTL.IN.ZS 
## Tipo de dato: numeric 
## Valores Completos: num_completos  ( 94.49 %)
## Valores NA: 181  ( 5.51 %)
## Resumen estadístico:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   8.461  39.547  57.450  57.264  75.373 100.000     181 
## Valores únicos: 2975
# Verificación de NAs en las variables cuantitativas (resumen final)
cat("\n Resumen de NAs y Valores Completos en variables cuantitativas\n")
## 
##  Resumen de NAs y Valores Completos en variables cuantitativas
na_summary_cuant <- sapply(datos[variables_cuantitativas], function(x) sum(is.na(x)))

# Crear un resumen de valores completos
completo_summary_cuant <- total_observaciones - na_summary_cuant

resumen_completo <- data.frame(
    Total_NA = na_summary_cuant,
    Valores_Completos = completo_summary_cuant
)
print(resumen_completo)
##                                                                                                     Total_NA
## Year                                                                                                       0
## Access.to.electricity....of.population....EG.ELC.ACCS.ZS                                                  94
## Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG                         721
## Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS               659
## Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS                                    67
## Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS                             193
## Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS                                    176
## Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS                             188
## Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5                                  1002
## Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS                                                               510
## Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS                                       1062
## Compulsory.education..duration..years....SE.COM.DURS                                                     308
## Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS                786
## Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS                  786
## Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS                                                169
## Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS                                                240
## GDP..current.US.....NY.GDP.MKTP.CD                                                                        41
## GDP.per.capita..current.US.....NY.GDP.PCAP.CD                                                             41
## General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS                             256
## Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS                                                   240
## Gross.savings....of.GDP....NY.GNS.ICTR.ZS                                                                513
## Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS                                                169
## Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG                                                   204
## Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS                               1061
## Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS                           225
## Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS                                                         921
## Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS                            516
## Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS                        0
## School.enrollment..preprimary....gross....SE.PRE.ENRR                                                    938
## School.enrollment..primary....gross....SE.PRM.ENRR                                                       504
## School.enrollment..secondary....gross....SE.SEC.ENRR                                                     857
## Trade....of.GDP....NE.TRD.GNFS.ZS                                                                        169
## Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX                                        76
## Prevalence.of.undernourishment.......SN_ITK_DEFC                                                        1453
## Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1                             1983
## Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK                     938
## Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK                    1930
## Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O                       1450
## Unemployment.rate..male.......SL_TLF_UEM                                                                1480
## Unemployment.rate..women.......SL_TLF_UEM                                                               1481
## Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF        2
## Gini.index..World.Bank.estimate....SI.POV.GINI                                                          1984
## Individuals.using.the.Internet....of.population....IT.NET.USER.ZS                                        301
## Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN                                                 191
## Population..total...SP.POP.TOTL                                                                          181
## Rural.population....of.total.population....SP.RUR.TOTL.ZS                                                  9
## Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS                                             234
## Urban.population....of.total.population....SP.URB.TOTL.IN.ZS                                             181
##                                                                                                     Valores_Completos
## Year                                                                                                             3287
## Access.to.electricity....of.population....EG.ELC.ACCS.ZS                                                         3193
## Adjusted.net.national.income.per.capita..annual...growth....NY.ADJ.NNTY.PC.KD.ZG                                 2566
## Adjusted.net.savings..excluding.particulate.emission.damage....of.GNI....NY.ADJ.SVNX.GN.ZS                       2628
## Adjusted.savings..carbon.dioxide.damage....of.GNI....NY.ADJ.DCO2.GN.ZS                                           3220
## Adjusted.savings..natural.resources.depletion....of.GNI....NY.ADJ.DRES.GN.ZS                                     3094
## Adjusted.savings..net.forest.depletion....of.GNI....NY.ADJ.DFOR.GN.ZS                                            3111
## Adjusted.savings..particulate.emission.damage....of.GNI....NY.ADJ.DPEM.GN.ZS                                     3099
## Automated.teller.machines..ATMs...per.100.000.adults....FB.ATM.TOTL.P5                                           2285
## Broad.money....of.GDP....FM.LBL.BMNY.GD.ZS                                                                       2777
## Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS                                                2225
## Compulsory.education..duration..years....SE.COM.DURS                                                             2979
## Cost.of.business.start.up.procedures..female....of.GNI.per.capita....IC.REG.COST.PC.FE.ZS                        2501
## Cost.of.business.start.up.procedures..male....of.GNI.per.capita....IC.REG.COST.PC.MA.ZS                          2501
## Exports.of.goods.and.services....of.GDP....NE.EXP.GNFS.ZS                                                        3118
## Final.consumption.expenditure....of.GDP....NE.CON.TOTL.ZS                                                        3047
## GDP..current.US.....NY.GDP.MKTP.CD                                                                               3246
## GDP.per.capita..current.US.....NY.GDP.PCAP.CD                                                                    3246
## General.government.final.consumption.expenditure....of.GDP....NE.CON.GOVT.ZS                                     3031
## Gross.national.expenditure....of.GDP....NE.DAB.TOTL.ZS                                                           3047
## Gross.savings....of.GDP....NY.GNS.ICTR.ZS                                                                        2774
## Imports.of.goods.and.services....of.GDP....NE.IMP.GNFS.ZS                                                        3118
## Inflation..consumer.prices..annual......FP.CPI.TOTL.ZG                                                           3083
## Primary.completion.rate..total....of.relevant.age.group....SE.PRM.CMPT.ZS                                        2226
## Proportion.of.seats.held.by.women.in.national.parliaments.......SG.GEN.PARL.ZS                                   3062
## Pupil.teacher.ratio..primary...SE.PRM.ENRL.TC.ZS                                                                 2366
## Renewable.electricity.output....of.total.electricity.output....EG.ELC.RNEW.ZS                                    2771
## Renewable.energy.consumption....of.total.final.energy.consumption....EG.FEC.RNEW.ZS                              3287
## School.enrollment..preprimary....gross....SE.PRE.ENRR                                                            2349
## School.enrollment..primary....gross....SE.PRM.ENRR                                                               2783
## School.enrollment..secondary....gross....SE.SEC.ENRR                                                             2430
## Trade....of.GDP....NE.TRD.GNFS.ZS                                                                                3118
## Women.Business.and.the.Law.Index.Score..scale.1.100....SG.LAW.INDX                                               3211
## Prevalence.of.undernourishment.......SN_ITK_DEFC                                                                 1834
## Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1                                      1304
## Proportion.of.population.covered.by.at.least.a.2G.mobile.network.......IT_MOB_2GNTWK                             2349
## Proportion.of.population.covered.by.at.least.a.3G.mobile.network.......IT_MOB_3GNTWK                             1357
## Proportion.of.population.using.basic.drinking.water.services.......SP_ACS_BSRVH2O                                1837
## Unemployment.rate..male.......SL_TLF_UEM                                                                         1807
## Unemployment.rate..women.......SL_TLF_UEM                                                                        1806
## Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF              3285
## Gini.index..World.Bank.estimate....SI.POV.GINI                                                                   1303
## Individuals.using.the.Internet....of.population....IT.NET.USER.ZS                                                2986
## Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN                                                         3096
## Population..total...SP.POP.TOTL                                                                                  3106
## Rural.population....of.total.population....SP.RUR.TOTL.ZS                                                        3278
## Total.natural.resources.rents....of.GDP....NY.GDP.TOTL.RT.ZS                                                     3053
## Urban.population....of.total.population....SP.URB.TOTL.IN.ZS                                                     3106
# 2.2 VARIABLES CUALITATIVAS

cat("\n2.2 ANÁLISIS DE VARIABLES CUALITATIVAS\n")
## 
## 2.2 ANÁLISIS DE VARIABLES CUALITATIVAS
# 1. Identificar variables cualitativas de tipo factor o character
# Incluyendo tanto las que R identifica como 'character' como las convertidas a 'factor'.
variables_cualitativas <- names(datos)[sapply(datos, function(x) is.factor(x) | is.character(x))]
cat("Variables cualitativas identificadas:", length(variables_cualitativas), "\n")
## Variables cualitativas identificadas: 9
cat("Lista:", paste(variables_cualitativas, collapse = ", "), "\n")
## Lista: Country, CountryCode, Continent, Income.Classification..World.Bank.Definition., Regime.Type..RoW.Measure.Definition., Region, Country.Name, Regime, Income
# Obtener el número total de filas para el cálculo de porcentajes
total_filas <- nrow(datos)
cat("Total de Filas en el Dataset:", total_filas, "\n")
## Total de Filas en el Dataset: 3287
# 2. Análisis detallado de cada variable cualitativa
for (var in variables_cualitativas) {
  cat("\n Análisis de", var, "\n")
  cat("Tipo de dato:", class(datos[[var]]), "\n")
  
  # Total de NA y CÁLCULO DEL PORCENTAJE
  num_na <- sum(is.na(datos[[var]]))
  porc_na <- round((num_na / total_filas) * 100, 2)
  
  # CÁLCULO DEL TOTAL DE VALORES COMPLETOS
  num_completos <- total_filas - num_na
  porc_completos <- 100 - porc_na
  
  cat("Valores Completos:", num_completos, " (", round(porc_completos, 2), "%)\n")
  cat("Valores NA:", num_na, " (", porc_na, "%)\n")
  
  # Detección de posibles errores o inconsistencias de datos
  
  # para responder desde el punto  2.2.1  al 2.2.5, haremos un Resumen de Frecuencias y Niveles
  # Usamos la función table() para ver la distribución de frecuencias
  frecuencias <- table(datos[[var]], useNA = "ifany") # Incluye NA si existen
  
  cat("Valores únicos (Niveles):", length(frecuencias) - ifelse(num_na > 0, 1, 0), "\n") 
  
  # Revisamos el resultado con un summary, para ver el detalle
  cat("Resumen de Frecuencias (Top Nivel y NAs):\n")
  print(head(summary(datos[[var]])))
  
  # Revisión de niveles con baja frecuencia
  # Mostramos un resumen de las frecuencias más comunes y menos comunes
  if (length(frecuencias) > 10) {
    cat("\n\n Top 5 Niveles más comunes:\n")
    print(head(sort(frecuencias, decreasing = TRUE), 5))
    cat("\n\n Top 5 Niveles menos comunes o posible ruido:\n")
    print(head(sort(frecuencias, decreasing = FALSE), 5))
  } else {
    cat("  Frecuencias de todos los niveles:\n")
    print(frecuencias)
  }
}
## 
##  Análisis de Country 
## Tipo de dato: character 
## Valores Completos: 3287  ( 100 %)
## Valores NA: 0  ( 0 %)
## Valores únicos (Niveles): 173 
## Resumen de Frecuencias (Top Nivel y NAs):
##    Length     Class      Mode 
##      3287 character character 
## 
## 
##  Top 5 Niveles más comunes:
## 
##             Albania             Algeria              Angola Antigua and Barbuda 
##                  19                  19                  19                  19 
##           Argentina 
##                  19 
## 
## 
##  Top 5 Niveles menos comunes o posible ruido:
## 
##             Albania             Algeria              Angola Antigua and Barbuda 
##                  19                  19                  19                  19 
##           Argentina 
##                  19 
## 
##  Análisis de CountryCode 
## Tipo de dato: factor 
## Valores Completos: 3287  ( 100 %)
## Valores NA: 0  ( 0 %)
## Valores únicos (Niveles): 173 
## Resumen de Frecuencias (Top Nivel y NAs):
## ABW AGO ALB ARE ARG ARM 
##  19  19  19  19  19  19 
## 
## 
##  Top 5 Niveles más comunes:
## 
## ABW AGO ALB ARE ARG 
##  19  19  19  19  19 
## 
## 
##  Top 5 Niveles menos comunes o posible ruido:
## 
## ABW AGO ALB ARE ARG 
##  19  19  19  19  19 
## 
##  Análisis de Continent 
## Tipo de dato: factor 
## Valores Completos: 3285  ( 99.94 %)
## Valores NA: 2  ( 0.06 %)
## Valores únicos (Niveles): 6 
## Resumen de Frecuencias (Top Nivel y NAs):
##        Africa          Asia        Europe North America       Oceania 
##           893           872           760           418           114 
## South America 
##           228 
##   Frecuencias de todos los niveles:
## 
##        Africa          Asia        Europe North America       Oceania 
##           893           872           760           418           114 
## South America          <NA> 
##           228             2 
## 
##  Análisis de Income.Classification..World.Bank.Definition. 
## Tipo de dato: character 
## Valores Completos: 3285  ( 99.94 %)
## Valores NA: 2  ( 0.06 %)
## Valores únicos (Niveles): 4 
## Resumen de Frecuencias (Top Nivel y NAs):
##    Length     Class      Mode 
##      3287 character character 
##   Frecuencias de todos los niveles:
## 
##         High income          Low income Lower-middle income Upper-middle income 
##                 899                 753                 868                 765 
##                <NA> 
##                   2 
## 
##  Análisis de Regime.Type..RoW.Measure.Definition. 
## Tipo de dato: character 
## Valores Completos: 3076  ( 93.58 %)
## Valores NA: 211  ( 6.42 %)
## Valores únicos (Niveles): 4 
## Resumen de Frecuencias (Top Nivel y NAs):
##    Length     Class      Mode 
##      3287 character character 
##   Frecuencias de todos los niveles:
## 
##    Closed Autocracy Electoral Autocracy Electoral Democracy   Liberal Democracy 
##                 409                 948                 993                 726 
##                <NA> 
##                 211 
## 
##  Análisis de Region 
## Tipo de dato: factor 
## Valores Completos: 3285  ( 99.94 %)
## Valores NA: 2  ( 0.06 %)
## Valores únicos (Niveles): 7 
## Resumen de Frecuencias (Top Nivel y NAs):
##        Central and Southern Asia   Eastern and South-Eastern Asia 
##                              228                              340 
##      Europe and Northern America      Latin America and Caribbean 
##                              779                              608 
## Northern Africa and Western Asia                          Oceania 
##                              399                              114 
##   Frecuencias de todos los niveles:
## 
##        Central and Southern Asia   Eastern and South-Eastern Asia 
##                              228                              340 
##      Europe and Northern America      Latin America and Caribbean 
##                              779                              608 
## Northern Africa and Western Asia                          Oceania 
##                              399                              114 
##               Sub-Saharan Africa                             <NA> 
##                              817                                2 
## 
##  Análisis de Country.Name 
## Tipo de dato: factor 
## Valores Completos: 3287  ( 100 %)
## Valores NA: 0  ( 0 %)
## Valores únicos (Niveles): 173 
## Resumen de Frecuencias (Top Nivel y NAs):
##             Albania             Algeria              Angola Antigua and Barbuda 
##                  19                  19                  19                  19 
##           Argentina             Armenia 
##                  19                  19 
## 
## 
##  Top 5 Niveles más comunes:
## 
##             Albania             Algeria              Angola Antigua and Barbuda 
##                  19                  19                  19                  19 
##           Argentina 
##                  19 
## 
## 
##  Top 5 Niveles menos comunes o posible ruido:
## 
##             Albania             Algeria              Angola Antigua and Barbuda 
##                  19                  19                  19                  19 
##           Argentina 
##                  19 
## 
##  Análisis de Regime 
## Tipo de dato: factor 
## Valores Completos: 3076  ( 93.58 %)
## Valores NA: 211  ( 6.42 %)
## Valores únicos (Niveles): 4 
## Resumen de Frecuencias (Top Nivel y NAs):
##    Closed Autocracy Electoral Autocracy Electoral Democracy   Liberal Democracy 
##                 409                 948                 993                 726 
##                NA's 
##                 211 
##   Frecuencias de todos los niveles:
## 
##    Closed Autocracy Electoral Autocracy Electoral Democracy   Liberal Democracy 
##                 409                 948                 993                 726 
##                <NA> 
##                 211 
## 
##  Análisis de Income 
## Tipo de dato: factor 
## Valores Completos: 3285  ( 99.94 %)
## Valores NA: 2  ( 0.06 %)
## Valores únicos (Niveles): 4 
## Resumen de Frecuencias (Top Nivel y NAs):
##         High income          Low income Lower-middle income Upper-middle income 
##                 899                 753                 868                 765 
##                NA's 
##                   2 
##   Frecuencias de todos los niveles:
## 
##         High income          Low income Lower-middle income Upper-middle income 
##                 899                 753                 868                 765 
##                <NA> 
##                   2
# 3. Resumen Consolidado de NAs y Valores Completos
cat("\n Resumen de NAs y Valores Completos en variables cualitativas\n")
## 
##  Resumen de NAs y Valores Completos en variables cualitativas
na_summary_cual <- sapply(datos[variables_cualitativas], function(x) sum(is.na(x)))

# Crear un resumen de valores completos
completo_summary_cual <- total_filas - na_summary_cual

resumen_completo_cual <- data.frame(
    Total_NA = na_summary_cual,
    Valores_Completos = completo_summary_cual
)
print(resumen_completo_cual)
##                                               Total_NA Valores_Completos
## Country                                              0              3287
## CountryCode                                          0              3287
## Continent                                            2              3285
## Income.Classification..World.Bank.Definition.        2              3285
## Regime.Type..RoW.Measure.Definition.               211              3076
## Region                                               2              3285
## Country.Name                                         0              3287
## Regime                                             211              3076
## Income                                               2              3285
# 3.1 DESIGUALDAD (GINI)

cat("\n3.1 ANÁLISIS DE LA DESIGUALDAD (ÍNDICE GINI)\n")
## 
## 3.1 ANÁLISIS DE LA DESIGUALDAD (ÍNDICE GINI)
# 3.1.1. Definir la variable GINI
var_gini <- "Gini.index..World.Bank.estimate....SI.POV.GINI"

# 1.1 Verificación de NAs
num_na_gini <- sum(is.na(datos[[var_gini]]))
total_obs <- nrow(datos)
porc_na_gini <- round((num_na_gini / total_obs) * 100, 2)

cat("Valores NA en GINI:", num_na_gini, " (", porc_na_gini, "% del total)\n")
## Valores NA en GINI: 1984  ( 60.36 % del total)
cat("Resumen estadístico de GINI:\n")
## Resumen estadístico de GINI:
print(summary(datos[[var_gini]]))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   23.70   30.90   35.60   37.51   42.80   64.80    1984
# 3.1.2. VISUALIZACIÓN DE LA DISTRIBUCIÓN

# Grafico de Histograma para ver la distribución general
p1 <- ggplot(datos, aes(x = .data[[var_gini]])) +
  geom_histogram(binwidth = 2, fill = "skyblue", color = "black", na.rm = TRUE) +
  labs(title = paste("Distribución del Índice GINI (N =", total_obs - num_na_gini, ")"),
       x = "Índice GINI", y = "Frecuencia") +
  theme_minimal()

# Grafico: Boxplot para ver la distribucion e indentificar valroes extremos
p2 <- ggplot(datos, aes(y = .data[[var_gini]])) +
  geom_boxplot(fill = "lightgreen", na.rm = TRUE) +
  labs(title = "Boxplot para detección de Extremos", y = "Índice GINI") +
  theme_minimal()

print(p1)

print(p2)

cat("\nINTERPRETACIÓN DEL GRÁFICO:\n")
## 
## INTERPRETACIÓN DEL GRÁFICO:
cat("Observar si la distribución es normal, sesgada (hacia izquierda o derecha) o bimodal.\n")
## Observar si la distribución es normal, sesgada (hacia izquierda o derecha) o bimodal.
cat("El boxplot muestra la mediana, cuartiles (Q1, Q3) y posibles valores atípicos (puntos fuera de los bigotes).\n")
## El boxplot muestra la mediana, cuartiles (Q1, Q3) y posibles valores atípicos (puntos fuera de los bigotes).
# 3.1.3. TRATAMIENTO DE VALORES EXTREMOS con Transformación Logarítmica

# Nota: La transformación logarítmica (log) se aplica típicamente a variables
# posiblemente sesgadas. Dado que el índice GINI (0-100) ya es acotado,
# la necesidad de una transformación puede ser menor, pero la aplicamos si el sesgo es fuerte y como ejemplo en este caso.

cat("\nAPLICANDO TRANSFORMACIÓN: Logaritmo\n")
## 
## APLICANDO TRANSFORMACIÓN: Logaritmo
# Crear una nueva columna para el GINI transformado, recordar que es posible usar mutate para esta accion.
datos$Gini_log <- log(datos[[var_gini]])

# 3.1.4. Visualización Post-Transformación para verificar el efecto
cat("\nVisualización de la distribución del GINI transformado (Log)\n")
## 
## Visualización de la distribución del GINI transformado (Log)
# hsitograma para comparar la evolucion y suavisacion de los datos ya que que la 
#logaritmacion es una suavisacion de datos, que ayuda a ver en grafico como histogramas la 
#informacion mas lineal y no tan distorcionada por valor atipicos
p3 <- ggplot(datos, aes(x = Gini_log)) +
  geom_histogram(binwidth = 0.05, fill = "salmon", color = "black", na.rm = TRUE) +
  labs(title = "Distribución del Índice GINI (Transformación Log)",
       x = "Log(Índice GINI)", y = "Frecuencia") +
  theme_minimal()

print(p3)

cat("\nINTERPRETACIÓN POST-TRANSFORMACIÓN:\n")
## 
## INTERPRETACIÓN POST-TRANSFORMACIÓN:
cat("El hgistograma nos muestra que tenemos una muestra con la mayor cantidad de la masa de datos entre los valores 30 y 40, es una masa unimodal on apenas un pico, tiene una ligera cola a la derecha hasta los valores 65 del eje x pero no es representativa, en el hsitograma de log (naranja) no vemos una suavisacion importante y en su lugar vemos que la distribucion pasa de ser unimodal a multimodal, manteniendo una cola a la derecha, lo que ha impedido mejorar la simetria de los datos; a esto le sumamos que el Boxplot muestra apena algunos valores extremos pero no fuera de rango, ayq ue se situan sobre valores de 65 aprox.\n")
## El hgistograma nos muestra que tenemos una muestra con la mayor cantidad de la masa de datos entre los valores 30 y 40, es una masa unimodal on apenas un pico, tiene una ligera cola a la derecha hasta los valores 65 del eje x pero no es representativa, en el hsitograma de log (naranja) no vemos una suavisacion importante y en su lugar vemos que la distribucion pasa de ser unimodal a multimodal, manteniendo una cola a la derecha, lo que ha impedido mejorar la simetria de los datos; a esto le sumamos que el Boxplot muestra apena algunos valores extremos pero no fuera de rango, ayq ue se situan sobre valores de 65 aprox.
cat("Usaremos la variable original 'Gini.index...' o 'Gini_log' en análisis posteriores según ya que es la mas adecuada.\n")
## Usaremos la variable original 'Gini.index...' o 'Gini_log' en análisis posteriores según ya que es la mas adecuada.
# 3.2 EMISIONES DE GAS DE EFECTO INVERNADERO

cat("\n3.2 ANÁLISIS DE EMISIONES DE co2 (Millones de Toneladas)\n")
## 
## 3.2 ANÁLISIS DE EMISIONES DE co2 (Millones de Toneladas)
# 3.2.1. Definir la variable de Emisiones de co2
var_co2 <- "Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF"

# 3.2.1.1 Verificación de NAs
num_na_co2 <- sum(is.na(datos[[var_co2]]))
total_obs <- nrow(datos)
porc_na_co2 <- round((num_na_co2 / total_obs) * 100, 2)

cat("Total de Observaciones:", total_obs, "\n")
## Total de Observaciones: 3287
cat("Valores NA en Emisiones co2:", num_na_co2, " (", porc_na_co2, " % del total)\n")
## Valores NA en Emisiones co2: 2  ( 0.06  % del total)
cat("Resumen estadístico de Emisiones co2 :\n")
## Resumen estadístico de Emisiones co2 :
print(summary(datos[[var_co2]]))
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##    0.048    2.426   12.621  174.647   72.012 9956.569        2
# 3.2.2. VISUALIZACIÓN DE LA DISTRIBUCIÓN

# Histograma para ver la forma de la distribución
p1 <- ggplot(datos, aes(x = .data[[var_co2]])) +
  geom_histogram(bins = 50, fill = "#FF5733", color = "black", na.rm = TRUE) +
  labs(title = paste("Distribución de Emisiones de co2 (N =", total_obs - num_na_co2, ")"),
       x = "Emisiones de co2 en Millones de Toneladas", y = "Frecuencia") +
  theme_minimal()

# Boxplot para detección de Extremos
p2 <- ggplot(datos, aes(y = .data[[var_co2]])) +
  geom_boxplot(fill = "salmon", na.rm = TRUE) +
  labs(title = "Boxplot para detección de Extremos en Emisiones co2", y = "Emisiones co2") +
  theme_minimal() +
  # Se añade una limitación en el eje Y para que los puntos atípicos sean visibles
  coord_cartesian(ylim = c(0, quantile(datos[[var_co2]], 0.995, na.rm = TRUE)))

print(p1)

print(p2)

cat("\nINTERPRETACIÓN DEL HISTOGRAMA:\n")
## 
## INTERPRETACIÓN DEL HISTOGRAMA:
cat("El histograma muestra un sesgo positivo extremo, con una consentracion masiva de datos a la izquierda y una larga cola de valores mayore a la derechay esto significa que la media y la desviación estandar son medidas muy poco representativas del conjunto de datos.\n")
## El histograma muestra un sesgo positivo extremo, con una consentracion masiva de datos a la izquierda y una larga cola de valores mayore a la derechay esto significa que la media y la desviación estandar son medidas muy poco representativas del conjunto de datos.
cat("El boxplot, incluso limitado, confirmara la presencia de numerosos valores extremos o atipicos, sin concentracion de masa de datos visual.\n")
## El boxplot, incluso limitado, confirmara la presencia de numerosos valores extremos o atipicos, sin concentracion de masa de datos visual.
# 3.2.3. TRANSFORMACIÓN LOGARÍTMICA
cat("\nAPLICANDO TRANSFORMACIÓN: Logaritmo (Base e) por el sesgo extremo detectado en los graficos anteriores.\n")
## 
## APLICANDO TRANSFORMACIÓN: Logaritmo (Base e) por el sesgo extremo detectado en los graficos anteriores.
# Creamos la nueva columna directamente
datos$CO2_log <- log(datos[[var_co2]] + 1)

# 3.2.4. Visualización Post-Transformación
cat("\nVisualización de la distribución de Emisiones $\\text{CO}_2$ transformadas (Log)\n")
## 
## Visualización de la distribución de Emisiones $\text{CO}_2$ transformadas (Log)
p3 <- ggplot(datos, aes(x = CO2_log)) +
  geom_histogram(binwidth = 0.5, fill = "#5B84B2", color = "black", na.rm = TRUE) +
  labs(title = "Distribución de Emisiones co2 (Transformación Log)",
       x = "Log(Emisiones co2 + 1)", y = "Frecuencia") +
  theme_minimal()

print(p3)

cat("\nINTERPRETACIÓN POST-TRANSFORMACIÓN:\n")
## 
## INTERPRETACIÓN POST-TRANSFORMACIÓN:
cat("Aunque no se convierte perfectamente en una campana de Gauss, la transformación ha comprimido los valores de co2 de las grandes economías y ha distribuido la frecuencia a lo largo de un rango más amplio\n")
## Aunque no se convierte perfectamente en una campana de Gauss, la transformación ha comprimido los valores de co2 de las grandes economías y ha distribuido la frecuencia a lo largo de un rango más amplio
# 3.2.5. DETECCIÓN DE VALORES EXTREMOS EN EL AÑO 2018 (Utilizando el IQR)

cat("\n5. DETECCIÓN DE PAÍSES MÁS CONTAMINANTES EN EL AÑO 2018\n")
## 
## 5. DETECCIÓN DE PAÍSES MÁS CONTAMINANTES EN EL AÑO 2018
# a) Filtrar datos del año 2018
datos_2018 <- datos[datos$Year == 2018, c("Country", var_co2)]
# Remover NAs (na.omit)
datos_2018 <- na.omit(datos_2018)

# b) Calcular el umbral de valores extremos (Criterio del Rango Intercuartílico - IQR)
Q1 <- quantile(datos_2018[[var_co2]], 0.25, na.rm = TRUE)
Q3 <- quantile(datos_2018[[var_co2]], 0.75, na.rm = TRUE)
IQR_val <- Q3 - Q1

# Un valor extremo superior (outlier) se define comúnmente como Q3 + 1.5 * IQR
umbral_extremo <- Q3 + 1.5 * IQR_val

cat(paste("Umbral de Emisión Extrema (Q3 + 1.5*IQR):", round(umbral_extremo, 2), "Millones de Toneladas\n"))
## Umbral de Emisión Extrema (Q3 + 1.5*IQR): 208.39 Millones de Toneladas
# c) Identificar y ordenar los países contaminantes
# Filtrar: seleccionar filas donde el valor de CO2 es mayor al umbral
filtro_extremo <- datos_2018[[var_co2]] > umbral_extremo
paises_contaminantes <- datos_2018[filtro_extremo, ]

# Ordenar de mayor a menor (descendente)
orden_descendente <- order(paises_contaminantes[[var_co2]], decreasing = TRUE)
paises_contaminantes <- paises_contaminantes[orden_descendente, ]

cat("\nLista de Países con Emisiones Extremadamente Grandes del Año 2018:\n")
## 
## Lista de Países con Emisiones Extremadamente Grandes del Año 2018:
# d) Visualizar la lista
print(head(paises_contaminantes))
##                 Country
## 608               China
## 3135      United States
## 1406              India
## 2584 Russian Federation
## 1577              Japan
## 1444 Iran, Islamic Rep.
##      Annual.production.based.emissions.of.carbon.dioxide..CO2..measured.in.million.tonnes...GH.EM.IC.LUF
## 608                                                                                             9956.569
## 3135                                                                                            5424.882
## 1406                                                                                            2591.324
## 2584                                                                                            1691.360
## 1577                                                                                            1135.688
## 1444                                                                                             755.402
cat("\n4 Correlaciones")
## 
## 4 Correlaciones
cat("\n4.1 CÁLCULO Y VISUALIZACIÓN DE LA MATRIZ DE CORRELACIONES\n")
## 
## 4.1 CÁLCULO Y VISUALIZACIÓN DE LA MATRIZ DE CORRELACIONES
# 4.1.1. Definir la lista de variables a analizar
# Para la correlación, las variables deben ser numéricas.
# ODS 1, 2, 3, 4, 10 y GDP
variables_pobreza_gdp <- c(
  "Prevalence.of.undernourishment.......SN_ITK_DEFC", # ODS 2: Desnutrición
  "Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1", # ODS 1: Pobreza Extrema
  "Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN", # ODS 3: Esperanza de vida (Salud)
  "Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS", # ODS 4: Niños fuera de la escuela
  "Gini.index..World.Bank.estimate....SI.POV.GINI", # ODS 10: Desigualdad Gini
  "GDP..current.US.....NY.GDP.MKTP.CD" # GDP
)

# 4.1.2. Subconjunto de datos para la correlación
datos_corr <- datos[ , variables_pobreza_gdp]

# 4.1.3. Asignar nombres cortos y claros para la matriz (facilita la interpretación)
nombres_cortos <- c("ODS2-Desnutricion", "ODS1-Pobreza_Extrema", "ODS3-Esperanza_Vida", 
                    "ODS4-Ninos_Fuera_Escuela", "ODS10-Indice_Gini", "GDP")

# Reemplazar los nombres largos en el subconjunto de datos
names(datos_corr) <- nombres_cortos

cat("Variables seleccionadas para la correlación:\n")
## Variables seleccionadas para la correlación:
print(names(datos_corr))
## [1] "ODS2-Desnutricion"        "ODS1-Pobreza_Extrema"    
## [3] "ODS3-Esperanza_Vida"      "ODS4-Ninos_Fuera_Escuela"
## [5] "ODS10-Indice_Gini"        "GDP"
# 4.1.4. Cálculo de la Matriz de Correlaciones
# Usamos la función cor() de R base.
# use="pairwise.complete.obs" maneja los NAs usando todos los pares de observaciones disponibles
# (es decir, calcula la correlación solo para las filas que tienen datos en ambos indicadores).
matriz_correlacion <- cor(datos_corr, use = "pairwise.complete.obs")

cat("\nMatriz de Correlaciones de Pearson:\n")
## 
## Matriz de Correlaciones de Pearson:
print(matriz_correlacion)
##                          ODS2-Desnutricion ODS1-Pobreza_Extrema
## ODS2-Desnutricion                1.0000000            0.6830318
## ODS1-Pobreza_Extrema             0.6830318            1.0000000
## ODS3-Esperanza_Vida             -0.5736113           -0.7651884
## ODS4-Ninos_Fuera_Escuela         0.4217590            0.6868922
## ODS10-Indice_Gini                0.1950710            0.3426187
## GDP                             -0.1727694           -0.1180153
##                          ODS3-Esperanza_Vida ODS4-Ninos_Fuera_Escuela
## ODS2-Desnutricion                 -0.5736113                0.4217590
## ODS1-Pobreza_Extrema              -0.7651884                0.6868922
## ODS3-Esperanza_Vida                1.0000000               -0.6612297
## ODS4-Ninos_Fuera_Escuela          -0.6612297                1.0000000
## ODS10-Indice_Gini                 -0.3529437                0.2043328
## GDP                                0.2021001               -0.1219929
##                          ODS10-Indice_Gini        GDP
## ODS2-Desnutricion                0.1950710 -0.1727694
## ODS1-Pobreza_Extrema             0.3426187 -0.1180153
## ODS3-Esperanza_Vida             -0.3529437  0.2021001
## ODS4-Ninos_Fuera_Escuela         0.2043328 -0.1219929
## ODS10-Indice_Gini                1.0000000  0.0121306
## GDP                              0.0121306  1.0000000
# 4.1.5. Interpretación de la Matriz (Resumen de Resultados)
cat("\nINTERPRETACIÓN DE LA MATRIZ DE CORRELACIÓN:\n")
## 
## INTERPRETACIÓN DE LA MATRIZ DE CORRELACIÓN:
cat("La matriz nos muestra que la variable desnutricion, se relaciona mas fuertemente con la variable de pobreza extrema ya que a menos desnutricion menos pobreza i al contrario, lo que es logico, pero la pobreza extrema se relacion fuertemente a su vez con la variable de escolarizacion, esto nos indica que entre menos pobresa menos desescolarizacion de niños\nLa variable de esperanza de vida tiene una relacion negativa o inversa con la pobreza extrema, ya que a menos pobreza mayor esperanza de vida\nEn cuanto a GDP o producto interno, las relaciones debiles nos dan a entender que la economica o su tamaño mejor dicho, no son el unico, ni mucho menos el principal elemnto que influye en la calidad de vida del este dataset")
## La matriz nos muestra que la variable desnutricion, se relaciona mas fuertemente con la variable de pobreza extrema ya que a menos desnutricion menos pobreza i al contrario, lo que es logico, pero la pobreza extrema se relacion fuertemente a su vez con la variable de escolarizacion, esto nos indica que entre menos pobresa menos desescolarizacion de niños
## La variable de esperanza de vida tiene una relacion negativa o inversa con la pobreza extrema, ya que a menos pobreza mayor esperanza de vida
## En cuanto a GDP o producto interno, las relaciones debiles nos dan a entender que la economica o su tamaño mejor dicho, no son el unico, ni mucho menos el principal elemnto que influye en la calidad de vida del este dataset
cat("\n4.2 ANÁLISIS DE CORRELACIONES CON ESPERANZA DE VIDA\n")
## 
## 4.2 ANÁLISIS DE CORRELACIONES CON ESPERANZA DE VIDA
# 4.2.1. Definimos la variable a usar
var_interes <- "ODS3-Esperanza_Vida"

# 4.2.2. Extraemos la columna de correlaciones para 'ODS3-Esperanza_Vida' de la matriz
# Usamos corchetes para seleccionar la fila o columna correspondiente.
correlaciones_vida <- matriz_correlacion[ , var_interes]

# 4.2.3. Eliminamos la correlación consigo misma ya que siempre da 1
# Usamos un vector lógico para excluir el elemento, recordar que la negacion de la igualdad es !=.
correlaciones_vida <- correlaciones_vida[names(correlaciones_vida) != var_interes]

# 4.2.4. Ordenamos las correlaciones de mayor a menor valor absoluto usando valores abs() para tomar el valor ignorando el signo de la correlacion.
# Luego usamos order() para obtener los índices, y finalemnte vamos a reordenar los datos.
orden_abs <- order(abs(correlaciones_vida), decreasing = TRUE)
correlaciones_ordenadas <- correlaciones_vida[orden_abs]

# 4.2.5. Convertimos a un data frame para poder tener una visualización mas clara y logica
tabla_correlaciones <- data.frame(
  Variable = names(correlaciones_ordenadas),
  Correlacion = as.numeric(correlaciones_ordenadas)
)

cat("\nTabla de Variables ordenadas por correlación con la ODS-3Esperanza de Vida:\n")
## 
## Tabla de Variables ordenadas por correlación con la ODS-3Esperanza de Vida:
# 4.2.6. Mostrar la tabla
print(tabla_correlaciones)
##                   Variable Correlacion
## 1     ODS1-Pobreza_Extrema  -0.7651884
## 2 ODS4-Ninos_Fuera_Escuela  -0.6612297
## 3        ODS2-Desnutricion  -0.5736113
## 4        ODS10-Indice_Gini  -0.3529437
## 5                      GDP   0.2021001
# 4.2.7. Interpretación
cat("\nINTERPRETACIÓN:\n")
## 
## INTERPRETACIÓN:
cat("La tabla muestra que la esperana de vida esta inversamente relacionada con las variables analizadas, muy interesante que la variable inversamente relacionada con mas fuerza es la pobreza extrema, seguida de la escolarizaciond e niños. Por otro lado es relevante que la variable con menos correlacion es la GBP o producto interno bruto, esto nos indica que un pais, pese a tener una gran volumen economico, este no efecta directamente a la longevidad de su poblacion; el indice GINI en este caso es perceptible lo uqe nos indica que la forma en la que se distribuye la riqueza o recursos importa y afecta de algun modo a la esperanza de vida de la poblacion.")
## La tabla muestra que la esperana de vida esta inversamente relacionada con las variables analizadas, muy interesante que la variable inversamente relacionada con mas fuerza es la pobreza extrema, seguida de la escolarizaciond e niños. Por otro lado es relevante que la variable con menos correlacion es la GBP o producto interno bruto, esto nos indica que un pais, pese a tener una gran volumen economico, este no efecta directamente a la longevidad de su poblacion; el indice GINI en este caso es perceptible lo uqe nos indica que la forma en la que se distribuye la riqueza o recursos importa y afecta de algun modo a la esperanza de vida de la poblacion.
# Cargar la librería VIM para la imputación knn
# El paquete VIM en R se usa para visualizar y tratar datos faltantes y su traduccion es Visualization and Imputation of Missing values, kNN(): imputación basada en vecinos más cercanos
library(VIM) 

cat("\n5. IMPUTACIÓN DE VALORES PERDIDOS EN ESPERANZA DE VIDA\n")
## 
## 5. IMPUTACIÓN DE VALORES PERDIDOS EN ESPERANZA DE VIDA
# Definimos la Variables, no olvidar copiar los nombres originales y pegarlo ya que son muy largos

var_esperanza <- "Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN"
var_year <- "Year"

cat("\n5.1 Revisamos los valores vacios por año en la variable esperanza de vida\n")
## 
## 5.1 Revisamos los valores vacios por año en la variable esperanza de vida
# Contar valores flotantes por año 
na_esperanza <- is.na(datos[[var_esperanza]])

# Agrupamos la suma de valores vacios por año, aqui buscamos ayuda en tutoriales y el codigo lo afinamos con ia de Brave.
na_por_año <- aggregate(na_esperanza, by = list(datos[[var_year]]), FUN = sum)
names(na_por_año) <- c("Year", "NA_Count")

cat("Conteo de vacios por año:\n")
## Conteo de vacios por año:
print(na_por_año)
##    Year NA_Count
## 1  2000      173
## 2  2001        2
## 3  2002        0
## 4  2003        1
## 5  2004        1
## 6  2005        1
## 7  2006        1
## 8  2007        1
## 9  2008        1
## 10 2009        1
## 11 2010        1
## 12 2011        1
## 13 2012        1
## 14 2013        1
## 15 2014        1
## 16 2015        1
## 17 2016        1
## 18 2017        1
## 19 2018        1
# asiganmos valores del 2001 a los vacios del 2000

cat("\n5.2 IMPUTACIÓN AÑO 2000: Usando el valor del año 2001\n")
## 
## 5.2 IMPUTACIÓN AÑO 2000: Usando el valor del año 2001
# a) Identificar el valor de Esperanza de Vida en 2001 (para cada país)
# Buscamos filas donde el AÑO es 2001 y la ESPERANZA DE VIDA NO esta vacio.
filtro_2001 <- datos[[var_year]] == 2001 & !is.na(datos[[var_esperanza]])
datos_2001 <- datos[filtro_2001, c("Country", var_esperanza)]

# b) Identificar las filas que necesitan imputación en 2000
filtro_2000_na <- datos[[var_year]] == 2000 & is.na(datos[[var_esperanza]])
filas_2000_na <- which(filtro_2000_na)

# c) Realizar la imputación usando un bucle siguiendo los ejemplos anteriores
for (i in filas_2000_na) {
  country_name <- datos[i, "Country"]
  
  # Buscar el valor de 2001 para ese país específico
  valor_2001 <- datos_2001[datos_2001$Country == country_name, var_esperanza]
  
  # Si se encuentra el valor de 2001
  if (length(valor_2001) == 1) {
    datos[i, var_esperanza] <- valor_2001
  }
}

cat("Número de valroes vacios imputados en 2000 usando de referencia los valores del 2001", sum(datos[filtro_2000_na, var_esperanza] != 0, na.rm = TRUE), "\n")
## Número de valroes vacios imputados en 2000 usando de referencia los valores del 2001 171
# 5.3 IMPUTACIÓN k-NN para el Resto de Años (Media de Vecinos Cercanos)

cat("\n5.3 IMPUTACIÓN k-NN: Usando 5 variables más correlacionadas\n")
## 
## 5.3 IMPUTACIÓN k-NN: Usando 5 variables más correlacionadas
variables_kNN <- c(variables_pobreza_gdp)

# Creamos un subconjunto con las variables relevantes para la imputación k-NN aprovechando la variable de variables_pobreza_gdp que generamos en el paso anterior
datos_imput_kNN <- datos[ , variables_kNN] 

# Aplicamos kNN. La función imputa la columna que contiene NAs en la variable var_esperanza
# usando las otras variables como 'vecinos'.
datos_imputados_VIM <- kNN(
  datos_imput_kNN, 
  variable = var_esperanza,
  k = 5
)
##                            Prevalence.of.undernourishment.......SN_ITK_DEFC 
##                                                                2.500000e+00 
## Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1 
##                                                                0.000000e+00 
##           Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS 
##                                                                0.000000e+00 
##                              Gini.index..World.Bank.estimate....SI.POV.GINI 
##                                                                2.370000e+01 
##                                          GDP..current.US.....NY.GDP.MKTP.CD 
##                                                                1.811170e+08 
##                            Prevalence.of.undernourishment.......SN_ITK_DEFC 
##                                                                6.750000e+01 
## Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1 
##                                                                9.430000e+01 
##           Children.out.of.school....of.primary.school.age....SE.PRM.UNER.ZS 
##                                                                7.310457e+01 
##                              Gini.index..World.Bank.estimate....SI.POV.GINI 
##                                                                6.480000e+01 
##                                          GDP..current.US.....NY.GDP.MKTP.CD 
##                                                                2.061190e+13
# 5.4. Actualización del Data Frame Original

# La función kNN de VIM añade columnas de 'imputación'. Solo necesitamos la columna imputada.
# Actualizamos la columna de Esperanza de Vida en el data frame original con los resultados imputados.
datos[[var_esperanza]] <- datos_imputados_VIM[[var_esperanza]]

cat("\nResumen Post-Imputación (Esperanza de Vida):\n")
## 
## Resumen Post-Imputación (Esperanza de Vida):
cat("Total de NAs iniciales:", num_na_co2, "\n")
## Total de NAs iniciales: 2
cat("Total de NAs restantes:", sum(is.na(datos[[var_esperanza]])), "\n")
## Total de NAs restantes: 0
cat("Resumen estadístico de la variable imputada:\n")
## Resumen estadístico de la variable imputada:
print(summary(datos[[var_esperanza]]))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   40.37   64.97   72.41   70.01   76.48   84.93
## CORRECCIÓN CRÍTICA DE TIPO DE DATO PARA LA SECCIÓN 6

cat("\ncorreccion del tipo de dato para la variable de pobreza extrema\n")
## 
## correccion del tipo de dato para la variable de pobreza extrema
var_pobreza <- "Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1"

# si no es numero que indique na
datos[[var_pobreza]] <- as.numeric(datos[[var_pobreza]])

cat("Tipo de dato de Pobreza Extrema después de la coerción:", class(datos[[var_pobreza]]), "\n")
## Tipo de dato de Pobreza Extrema después de la coerción: numeric
cat("Nuevos valores de tipo na generados:", sum(is.na(datos[[var_pobreza]])) - sum(is.na(datos[[var_pobreza]])), "\n")
## Nuevos valores de tipo na generados: 0
cat("\n6. TABLAS RESUMEN DE TENDENCIA CENTRAL Y DISPERSIÓN POR REGIÓN\n")
## 
## 6. TABLAS RESUMEN DE TENDENCIA CENTRAL Y DISPERSIÓN POR REGIÓN
# 6.1. Definición de Variables y Funciones
variables_analisis <- c(
"Proportion.of.population.below.international.poverty.line.......SI_POV_DAY1",
"Gini.index..World.Bank.estimate....SI.POV.GINI",
"Life.expectancy.at.birth..total..years....SP.DYN.LE00.IN"
)
nombres_tabla <- c("Pobreza_Extrema", "Indice_Gini", "Esperanza_Vida")

# Funciones de resumen
calcular_media <- function(x) { mean(x, na.rm = TRUE) }
calcular_mediana <- function(x) { median(x, na.rm = TRUE) }
calcular_sd <- function(x) { sd(x, na.rm = TRUE) }
calcular_mad <- function(x) { mad(x, na.rm = TRUE) }

# 6.2. Filtrado del ultimo año, ordenandolo de forma decreciente
orden_datos <- order(datos$Country, datos$Year, decreasing = TRUE)
datos_ordenados <- datos[orden_datos, ]
datos_ultimo_pais <- datos_ordenados[!duplicated(datos_ordenados$Country), ]
# Aseguramos que datos_final se crea ANTES de usarse, dado a los errores en las versiones anteriores de codigo
datos_final <- subset(datos_ultimo_pais, !is.na(Region)) 

regiones_unicas <- sort(unique(datos_final$Region))
cat("\n6.3 Tabala de tendencia central por region\n") #esta version tiene corregidos los errores por dimension que nos saltaron en las versiones 16 y 18 del codigo
## 
## 6.3 Tabala de tendencia central por region
funciones_central <- list(Media = calcular_media, Mediana = calcular_mediana)

# Calculo de la lista para los resultados
tabla_central_list <- lapply(variables_analisis, function(var) {
  
  filtro_na_var <- !is.na(datos_final[[var]])
  datos_filtrados <- as.numeric(datos_final[[var]][filtro_na_var])
  region_filtrada <- datos_final$Region[filtro_na_var]
  
  # 6.3.1. Ejecutamos tapply
  resultados_tapply <- tapply(datos_filtrados, region_filtrada, 
                       function(x) {
                         # Genera los dos resultados
                         res <- sapply(funciones_central, function(f) f(x))
                         return(res)
                       })
  
  # 6.3.2. Convertir los resultados de la lista tapply a un data frame, con dos columnas
  
  # Nombres para las columnas creadas
  nombres_columnas <- names(funciones_central)
  
  # estructura para las filas, rellenando los campos con na si no existen
  df_resultados <- do.call(rbind, lapply(resultados_tapply, function(x) {
    if (is.null(x)) {
      # Para cuando una región esta sin datos
      x <- rep(NA, length(nombres_columnas))
      names(x) <- nombres_columnas
    } else if (length(x) == 1) {
      # por si se calcula solo una de las dos medidas
      y <- rep(NA, length(nombres_columnas))
      names(y) <- nombres_columnas
      y[names(x)] <- x # ubciar el valor correcto en el sitio que corresponde
      x <- y
    }
    # Aseguramos que el vector resultante es una fila con los nombres correctos
    as.data.frame(t(x)) 
  }))
  
  # 3. Asignar nombres de fila como regiones, usando los nombres de las lista de resultados_tapply
  rownames(df_resultados) <- names(resultados_tapply)
  
  # Retornar la matriz
  return(as.matrix(df_resultados)) 
})
names(tabla_central_list) <- variables_analisis

lista_dfs_central <- lapply(1:length(variables_analisis), function(i) {
    nombre <- nombres_tabla[i]
    matriz_temp <- tabla_central_list[[i]]
    
    # Correccion apra matriz vacia o con valores flotantes
    if (nrow(matriz_temp) == 0) {
        return(NULL)
    } else {
        df_temp <- data.frame(Region = rownames(matriz_temp),
                              Matriz_Media = matriz_temp[, 1],
                              Matriz_Mediana = matriz_temp[, 2],
                              stringsAsFactors = FALSE)
        
        names(df_temp)[2] <- paste0("Media_", nombre)
        names(df_temp)[3] <- paste0("Mediana_", nombre)
        
        return(df_temp)
    }
})

# Iniciamos la tabla base con las regiones unicas
tabla_central <- data.frame(Region = regiones_unicas, stringsAsFactors = FALSE)

# Eliminamos cualquier elemento vacion o NULL de la lista
lista_dfs_central <- lista_dfs_central[!sapply(lista_dfs_central, is.null)]

# Fusionamos la tabla base con la lista de resultados usando Reduce y merge
if (length(lista_dfs_central) > 0) {
    tabla_central <- Reduce(function(x, y) merge(x, y, by = "Region", all.x = TRUE), 
                            lista_dfs_central, 
                            init = tabla_central)
}

tabla_central <- tabla_central[order(tabla_central$Region), ]
cat("\nTabla de Tendencia Central:\n")
## 
## Tabla de Tendencia Central:
print(tabla_central)
##                             Region Media_Pobreza_Extrema
## 1        Central and Southern Asia             1.3750000
## 2   Eastern and South-Eastern Asia             3.1000000
## 3      Europe and Northern America             0.4483871
## 4      Latin America and Caribbean             3.2071429
## 5 Northern Africa and Western Asia             1.1800000
## 6                          Oceania                    NA
## 7               Sub-Saharan Africa            33.1250000
##   Mediana_Pobreza_Extrema Media_Indice_Gini Mediana_Indice_Gini
## 1                    0.55          32.27500                29.7
## 2                    2.25          37.28333                37.1
## 3                    0.20          31.00323                30.2
## 4                    1.70          45.39286                45.4
## 5                    0.00          34.28000                34.4
## 6                      NA                NA                  NA
## 7                   41.05          38.55000                35.4
##   Media_Esperanza_Vida Mediana_Esperanza_Vida
## 1             72.47567               71.51650
## 2             75.41964               75.51950
## 3             79.14412               80.89268
## 4             74.21138               74.74400
## 5             76.02221               76.45300
## 6             74.31789               71.81800
## 7             62.58853               62.97300