Este trabajo fue elaborado con el propósito de analisar el departamento de Guainia y los principales indicadores demográficos de su población, tomando como base el censo nacional del año 2018. De manera que podamos visualizar e interpretar asertivamente su estructura poblacional.

Para este estudio tendremos en cuenta los siguientes índices:

Índice de envejecimiento: proporción de adultos mayores que encontramos en la población total. Índice de sobreenvejecimiento:proporción de personas de 80 años o más dentro del grupo de adultos mayores. Índice de feminización: población femenina por grupo de edad. relación de dependencia de vejez: proporción de población mayor, frente a la población económicamente activa. Índice de dependencia, que abarca tanto a jóvenes como a mayores en relación con la población económicamente activa. Relación de masculinidad y relación femenina: Distribución de la población por sexo en el departamento de Guainía.

A lo largo del análisis de población se profundizará en indicadores adicionales que resuten valiosos para el estudio.

######CARGAMOS LAS LIBRERÍAS

#####CARGAMOS LA BASE DE DATOS Y LOS MICRODATOS

Estas líneas de código están enfocadas en la carga de datos censales (personas, hogares, viviendas) del departamento de Guainía. Una vez cargados, se organizan los nombres de las columnas de cada archivo para inspeccionar qué variables están disponibles en los datasets. Esta es una parte inicial del análisis, donde podremos revisar los datos y prepararlos para ser utilizados en las estimaciones demográficas.

setwd("C:/Users/mpaul/Downloads/94_Guainia_CSV")

# Se cargan los microdatos Cundinamarca
CNPV2018_1VIV_A2_94 <- read_csv("CNPV2018_1VIV_A2_94.CSV")
## Rows: 11506 Columns: 30
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (1): U_MPIO
## dbl (29): TIPO_REG, U_DPTO, UA_CLASE, U_EDIFICA, COD_ENCUESTAS, U_VIVIENDA, ...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
CNPV2018_5PER_A2_94 <- read_csv("CNPV2018_5PER_A2_94.CSV")
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
##   dat <- vroom(...)
##   problems(dat)
## Rows: 44431 Columns: 48
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (1): U_MPIO
## dbl (44): TIPO_REG, U_DPTO, UA_CLASE, COD_ENCUESTAS, U_VIVIENDA, P_NROHOG, P...
## lgl  (3): PA12_CLAN, PA21_COD_VITSA, PA22_COD_KUMPA
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
CNPV2018_2HOG_A2_94 <- read_csv("CNPV2018_2HOG_A2_94.CSV")
## Rows: 10055 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (1): U_MPIO
## dbl (12): TIPO_REG, U_DPTO, UA_CLASE, COD_ENCUESTAS, U_VIVIENDA, H_NROHOG, H...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
CNPV2018_MGN_A2_94 <- read_csv("CNPV2018_MGN_A2_94.CSV")
## Rows: 11506 Columns: 14
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (7): U_MPIO, U_SECT_RUR, U_SECC_RUR, UA2_CPOB, U_SECT_URB, U_SECC_URB, U...
## dbl (7): U_DPTO, UA_CLASE, UA1_LOCALIDAD, U_EDIFICA, COD_ENCUESTAS, U_VIVIEN...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Variables
names(CNPV2018_5PER_A2_94)
##  [1] "TIPO_REG"         "U_DPTO"           "U_MPIO"           "UA_CLASE"        
##  [5] "COD_ENCUESTAS"    "U_VIVIENDA"       "P_NROHOG"         "P_NRO_PER"       
##  [9] "P_SEXO"           "P_EDADR"          "P_PARENTESCOR"    "PA1_GRP_ETNIC"   
## [13] "PA11_COD_ETNIA"   "PA12_CLAN"        "PA21_COD_VITSA"   "PA22_COD_KUMPA"  
## [17] "PA_HABLA_LENG"    "PA1_ENTIENDE"     "PB_OTRAS_LENG"    "PB1_QOTRAS_LENG" 
## [21] "PA_LUG_NAC"       "PA_VIVIA_5ANOS"   "PA_VIVIA_1ANO"    "P_ENFERMO"       
## [25] "P_QUEHIZO_PPAL"   "PA_LO_ATENDIERON" "PA1_CALIDAD_SERV" "CONDICION_FISICA"
## [29] "P_ALFABETA"       "PA_ASISTENCIA"    "P_NIVEL_ANOSR"    "P_TRABAJO"       
## [33] "P_EST_CIVIL"      "PA_HNV"           "PA1_THNV"         "PA2_HNVH"        
## [37] "PA3_HNVM"         "PA_HNVS"          "PA1_THSV"         "PA2_HSVH"        
## [41] "PA3_HSVM"         "PA_HFC"           "PA1_THFC"         "PA2_HFCH"        
## [45] "PA3_HFCM"         "PA_UHNV"          "PA1_MES_UHNV"     "PA2_ANO_UHNV"
names(CNPV2018_2HOG_A2_94)
##  [1] "TIPO_REG"         "U_DPTO"           "U_MPIO"           "UA_CLASE"        
##  [5] "COD_ENCUESTAS"    "U_VIVIENDA"       "H_NROHOG"         "H_NRO_CUARTOS"   
##  [9] "H_NRO_DORMIT"     "H_DONDE_PREPALIM" "H_AGUA_COCIN"     "HA_NRO_FALL"     
## [13] "HA_TOT_PER"
names(CNPV2018_MGN_A2_94)
##  [1] "U_DPTO"        "U_MPIO"        "UA_CLASE"      "UA1_LOCALIDAD"
##  [5] "U_SECT_RUR"    "U_SECC_RUR"    "UA2_CPOB"      "U_SECT_URB"   
##  [9] "U_SECC_URB"    "U_MZA"         "U_EDIFICA"     "COD_ENCUESTAS"
## [13] "U_VIVIENDA"    "COD_DANE_ANM"
names(CNPV2018_1VIV_A2_94)
##  [1] "TIPO_REG"          "U_DPTO"            "U_MPIO"           
##  [4] "UA_CLASE"          "U_EDIFICA"         "COD_ENCUESTAS"    
##  [7] "U_VIVIENDA"        "UVA_ESTATER"       "UVA1_TIPOTER"     
## [10] "UVA2_CODTER"       "UVA_ESTA_AREAPROT" "UVA1_COD_AREAPROT"
## [13] "UVA_USO_UNIDAD"    "V_TIPO_VIV"        "V_CON_OCUP"       
## [16] "V_TOT_HOG"         "V_MAT_PARED"       "V_MAT_PISO"       
## [19] "VA_EE"             "VA1_ESTRATO"       "VB_ACU"           
## [22] "VC_ALC"            "VD_GAS"            "VE_RECBAS"        
## [25] "VE1_QSEM"          "VF_INTERNET"       "V_TIPO_SERSA"     
## [28] "L_TIPO_INST"       "L_EXISTEHOG"       "L_TOT_PERL"

######PARA EL ANÁLISIS DE LOS INDÍCADORES DEMOGRÁFICOS DEBEMOS FILTRAR Y SELECCIONAR LA INFORMACIÓN DE LOS MUNICIPIOS DE GUAINÍA

En el siguiente espacio esperamos seleccionar y etiquetar los datos de personas, hogares y áreas geográficas de los municipios de Guainía. Este paso es clave para asegurar que el análisis se limite a las áreas de interés y que los resultados puedan ser más claros, precisos y fáciles de interpretar. Las etiquetas asignadas a los municipios también mejoran la legibilidad de los datos.

# Selección Mcpios AM en la tabla Personas
censo18per_AM94 = CNPV2018_5PER_A2_94 %>%
  filter(U_DPTO == "94" & U_MPIO %in% c("001", "883","343", "888", "884"))
# Asignación Iniciales Mcpios AM
censo18per_AM94$nmpio <- factor(censo18per_AM94$U_MPIO, labels = c("PTINI","SANFE","BMINS","MCHAL", 
                                                                   "PTCOL"))
# Selección Mcpios AM en la tabla Hogares
censo18hog_AM94 = CNPV2018_2HOG_A2_94 %>%
  filter(U_DPTO == "94" & U_MPIO %in% c("001", "883","343", "888", "884"))

# Selección Mcpios AM en la tabla MGN
censo18mgn_AM94 = CNPV2018_MGN_A2_94 %>%
  filter(U_DPTO == "94" & U_MPIO %in% c("001", "883","343", "888", "884"))

######CREAMOS EL IDENTIFICADOR ÚNICO

Se crea un identificador único para cada sección geográfica combinando el código de departamento y municipio. Se genera un identificador único para cada hogar mediante la concatenación de códigos de encuesta y número de hogar. Se crea un identificador único para cada persona combinando códigos de encuesta y número de persona en el hogar.

# Se crea el identificador único de la sección MGN
censo18mgn_AM94$ID_DPMP <- paste(censo18mgn_AM94$U_DPTO, 
                                 censo18mgn_AM94$U_MPIO, sep = "")
censo18mgn_AM94  <- censo18mgn_AM94[, -c(1:11, 13:14)]
censo18mgn_AM94$ID_DPMP <- as.character(censo18mgn_AM94$ID_DPMP)

# Creación de un identificador único por Hogares (concatena cod_encuesta y h_nrohog)
censo18hog_AM94$ID_HOG_UNIC <- paste(censo18hog_AM94$COD_ENCUESTAS, 
                                     censo18hog_AM94$H_NROHOG, sep = "-")

# Creación de un identificador único por persona (concatena cod_encuesta y p_nrohog)
censo18per_AM94$ID_HOG_UNIC <- paste(censo18per_AM94$COD_ENCUESTAS, 
                                     censo18per_AM94$P_NROHOG, sep = "-")

Se unen las tablas de personas y geografía (censo18mgn_AM94 y censo18per_AM94) por el código de encuesta. Se eliminan columnas duplicadas tras la unión. Se unen las tablas de personas-geografía con la de hogares (censo18hog_AM94) usando el identificador único del hogar. Se genera un identificador único para cada persona dentro del hogar.

# Unión entre las tablas censo18mgn_AM94 y censo18per_AM94
Per_Mgn <- merge(censo18mgn_AM94, censo18per_AM94, by = "COD_ENCUESTAS")
Per_Mgn$ID_HOG_UNIC <- as.character(Per_Mgn$ID_HOG_UNIC)

# Elimina las columnas comunes entre Per_Mgn y censo18hog_AM94
Per_Mgn <- Per_Mgn[, -c(1, 3:7)]

# Unión entre las tablas Per_Mgn y censo18hog_AM94
Per_Mgn_Hog <- merge(Per_Mgn, censo18hog_AM94, by = "ID_HOG_UNIC")
Per_Mgn_Hog$ID_PER_UNIC <- paste(Per_Mgn_Hog$ID_HOG_UNIC, 
                                 Per_Mgn_Hog$P_NRO_PER, sep = "-")

#####IDENTIFICADOR DE DATOS FALTANTES

Cuenta los valores faltantes por columna. Calcula el porcentaje de datos faltantes por columna. Ordena las columnas según el porcentaje de datos faltantes.

colSums(is.na(Per_Mgn_Hog))
##      ID_HOG_UNIC          ID_DPMP         P_NROHOG        P_NRO_PER 
##                0                0             6056                0 
##           P_SEXO          P_EDADR    P_PARENTESCOR    PA1_GRP_ETNIC 
##                0                0             6056                0 
##   PA11_COD_ETNIA        PA12_CLAN   PA21_COD_VITSA   PA22_COD_KUMPA 
##            10453            41177            41176            41177 
##    PA_HABLA_LENG     PA1_ENTIENDE    PB_OTRAS_LENG  PB1_QOTRAS_LENG 
##            15328            36575            15328            39735 
##       PA_LUG_NAC   PA_VIVIA_5ANOS    PA_VIVIA_1ANO        P_ENFERMO 
##                0             6056             6056             6056 
##   P_QUEHIZO_PPAL PA_LO_ATENDIERON PA1_CALIDAD_SERV CONDICION_FISICA 
##            37305            38627            38842             6056 
##       P_ALFABETA    PA_ASISTENCIA    P_NIVEL_ANOSR        P_TRABAJO 
##             3923             9974             3923            14130 
##      P_EST_CIVIL           PA_HNV         PA1_THNV         PA2_HNVH 
##            10186            28044            33223            33223 
##         PA3_HNVM          PA_HNVS         PA1_THSV         PA2_HSVH 
##            33223            33223            33364            33364 
##         PA3_HSVM           PA_HFC         PA1_THFC         PA2_HFCH 
##            33364            33223            39463            39463 
##         PA3_HFCM          PA_UHNV     PA1_MES_UHNV     PA2_ANO_UHNV 
##            39463            33223            35152            35152 
##            nmpio         TIPO_REG           U_DPTO           U_MPIO 
##                0                0                0                0 
##         UA_CLASE    COD_ENCUESTAS       U_VIVIENDA         H_NROHOG 
##                0                0                0             6056 
##    H_NRO_CUARTOS     H_NRO_DORMIT H_DONDE_PREPALIM     H_AGUA_COCIN 
##             6056             6056             6056             6514 
##      HA_NRO_FALL       HA_TOT_PER      ID_PER_UNIC 
##            40375             6056                0
porcentajeMiss <- function(x) {sum(is.na(x)) / length(x) * 100}
sort(apply(Per_Mgn_Hog, 2, porcentajeMiss))
##      ID_HOG_UNIC          ID_DPMP        P_NRO_PER           P_SEXO 
##         0.000000         0.000000         0.000000         0.000000 
##          P_EDADR    PA1_GRP_ETNIC       PA_LUG_NAC            nmpio 
##         0.000000         0.000000         0.000000         0.000000 
##         TIPO_REG           U_DPTO           U_MPIO         UA_CLASE 
##         0.000000         0.000000         0.000000         0.000000 
##    COD_ENCUESTAS       U_VIVIENDA      ID_PER_UNIC       P_ALFABETA 
##         0.000000         0.000000         0.000000         9.527163 
##    P_NIVEL_ANOSR         P_NROHOG    P_PARENTESCOR   PA_VIVIA_5ANOS 
##         9.527163        14.707239        14.707239        14.707239 
##    PA_VIVIA_1ANO        P_ENFERMO CONDICION_FISICA         H_NROHOG 
##        14.707239        14.707239        14.707239        14.707239 
##    H_NRO_CUARTOS     H_NRO_DORMIT H_DONDE_PREPALIM       HA_TOT_PER 
##        14.707239        14.707239        14.707239        14.707239 
##     H_AGUA_COCIN    PA_ASISTENCIA      P_EST_CIVIL   PA11_COD_ETNIA 
##        15.819511        24.222260        24.737111        25.385531 
##        P_TRABAJO    PA_HABLA_LENG    PB_OTRAS_LENG           PA_HNV 
##        34.315273        37.224664        37.224664        68.105981 
##         PA1_THNV         PA2_HNVH         PA3_HNVM          PA_HNVS 
##        80.683391        80.683391        80.683391        80.683391 
##           PA_HFC          PA_UHNV         PA1_THSV         PA2_HSVH 
##        80.683391        80.683391        81.025815        81.025815 
##         PA3_HSVM     PA1_MES_UHNV     PA2_ANO_UHNV     PA1_ENTIENDE 
##        81.025815        85.368045        85.368045        88.823858 
##   P_QUEHIZO_PPAL PA_LO_ATENDIERON PA1_CALIDAD_SERV         PA1_THFC 
##        90.596692        93.807222        94.329359        95.837482 
##         PA2_HFCH         PA3_HFCM  PB1_QOTRAS_LENG      HA_NRO_FALL 
##        95.837482        95.837482        96.498045        98.052311 
##   PA21_COD_VITSA        PA12_CLAN   PA22_COD_KUMPA 
##        99.997571       100.000000       100.000000

#####SELECCIÓN DE VARIABLES Se eliminan columnas específicas del dataset Per_Mgn_Hog para simplificar y dejar solo las variables necesarias para el análisis.

Per_Mgn_Hog <- Per_Mgn_Hog[, -c(9:16,21:23,30:44,57:58)]

######CALCULAR INDICADORES DE DEPARTAMENTO, MUNICIPIO Y VIVIENDA Este bloque de código realiza el cálculo de varios índicadores demográficos y educativos a nivel de departamento y municipio usando una consulta sobre el dataset Per_Mgn_Hog. Entre los indicadores calculados están:

Distribución por edad y sexo: Se suman las personas por rangos de edad y sexo (Hombres y Mujeres) usando condiciones IIF. Nivel educativo: Se agrupan por los distintos niveles de escolaridad alcanzados. Estado civil: Se calcula la cantidad de personas por estado civil. Relación con el jefe de hogar: Se identifican los miembros del hogar en función de su parentesco con el jefe del hogar. Número de viviendas: Se cuenta el número total de viviendas.

################### CONTEOS PERSONA - HOGAR - VIVIENDA #########################

#------ Calculo de los indicadores a nivel de departamento -----#
consulta_PersonaHogar= "select U_DPTO, U_MPIO, UA_CLASE,
              sum(IIF(P_SEXO = 1 and P_EDADR=1, 1.0,0)) as H_00_04,
              sum(IIF(P_SEXO = 1 and P_EDADR=2, 1.0,0)) as H_05_09,
              sum(IIF(P_SEXO = 1 and P_EDADR=3, 1.0,0)) as H_10_14,
              sum(IIF(P_SEXO = 1 and P_EDADR=4, 1.0,0)) as H_15_19,
              sum(IIF(P_SEXO = 1 and P_EDADR=5, 1.0,0)) as H_20_24,
              sum(IIF(P_SEXO = 1 and P_EDADR=6, 1.0,0)) as H_25_29,
              sum(IIF(P_SEXO = 1 and P_EDADR=7, 1.0,0)) as H_30_34,
              sum(IIF(P_SEXO = 1 and P_EDADR=8, 1.0,0)) as H_35_39,
              sum(IIF(P_SEXO = 1 and P_EDADR=9, 1.0,0)) as H_40_44,
              sum(IIF(P_SEXO = 1 and P_EDADR=10, 1.0,0)) as H_45_49,
              sum(IIF(P_SEXO = 1 and P_EDADR=11, 1.0,0)) as H_50_54,
              sum(IIF(P_SEXO = 1 and P_EDADR=12, 1.0,0)) as H_55_59,
              sum(IIF(P_SEXO = 1 and P_EDADR=13, 1.0,0)) as H_60_64,
              sum(IIF(P_SEXO = 1 and P_EDADR=14, 1.0,0)) as H_65_69,
              sum(IIF(P_SEXO = 1 and P_EDADR=15, 1.0,0)) as H_70_74,
              sum(IIF(P_SEXO = 1 and P_EDADR=16, 1.0,0)) as H_75_79,
              sum(IIF(P_SEXO = 1 and P_EDADR=17, 1.0,0)) as H_80_84,
              sum(IIF(P_SEXO = 1 and P_EDADR=18, 1.0,0)) as H_85_89,
              sum(IIF(P_SEXO = 1 and P_EDADR=19, 1.0,0)) as H_90_94,
              sum(IIF(P_SEXO = 1 and P_EDADR=20, 1.0,0)) as H_95_99,
              sum(IIF(P_SEXO = 1 and P_EDADR=21, 1.0,0)) as H_100_104,
              sum(IIF(P_SEXO = 2 and P_EDADR=1, 1.0,0)) as M_00_04,
              sum(IIF(P_SEXO = 2 and P_EDADR=2, 1.0,0)) as M_05_09,
              sum(IIF(P_SEXO = 2 and P_EDADR=3, 1.0,0)) as M_10_14,
              sum(IIF(P_SEXO = 2 and P_EDADR=4, 1.0,0)) as M_15_19,
              sum(IIF(P_SEXO = 2 and P_EDADR=5, 1.0,0)) as M_20_24,
              sum(IIF(P_SEXO = 2 and P_EDADR=6, 1.0,0)) as M_25_29,
              sum(IIF(P_SEXO = 2 and P_EDADR=7, 1.0,0)) as M_30_34,
              sum(IIF(P_SEXO = 2 and P_EDADR=8, 1.0,0)) as M_35_39,
              sum(IIF(P_SEXO = 2 and P_EDADR=9, 1.0,0)) as M_40_44,
              sum(IIF(P_SEXO = 2 and P_EDADR=10, 1.0,0)) as M_45_49,
              sum(IIF(P_SEXO = 2 and P_EDADR=11, 1.0,0)) as M_50_54,
              sum(IIF(P_SEXO = 2 and P_EDADR=12, 1.0,0)) as M_55_59,
              sum(IIF(P_SEXO = 2 and P_EDADR=13, 1.0,0)) as M_60_64,
              sum(IIF(P_SEXO = 2 and P_EDADR=14, 1.0,0)) as M_65_69,
              sum(IIF(P_SEXO = 2 and P_EDADR=15, 1.0,0)) as M_70_74,
              sum(IIF(P_SEXO = 2 and P_EDADR=16, 1.0,0)) as M_75_79,
              sum(IIF(P_SEXO = 2 and P_EDADR=17, 1.0,0)) as M_80_84,
              sum(IIF(P_SEXO = 2 and P_EDADR=18, 1.0,0)) as M_85_89,
              sum(IIF(P_SEXO = 2 and P_EDADR=19, 1.0,0)) as M_90_94,
              sum(IIF(P_SEXO = 2 and P_EDADR=20, 1.0,0)) as M_95_99,
              sum(IIF(P_SEXO = 2 and P_EDADR=21, 1.0,0)) as M_100_104,
              sum(IIF(P_SEXO = 1,1.0,0)) as Hombres,
              sum(IIF(P_SEXO = 2,1.0,0)) as Mujeres,
              sum(IIF(P_NIVEL_ANOSR = 1, 1.0,0)) as Prescolar,
              sum(IIF(P_NIVEL_ANOSR = 2, 1.0,0)) as BPrimaria,
              sum(IIF(P_NIVEL_ANOSR = 3, 1.0,0)) as BSecundaria,
              sum(IIF(P_NIVEL_ANOSR = 4, 1.0,0)) as MAcademica,
              sum(IIF(P_NIVEL_ANOSR = 5, 1.0,0)) as MTecnica,
              sum(IIF(P_NIVEL_ANOSR = 6, 1.0,0)) as Normalista,
              sum(IIF(P_NIVEL_ANOSR = 7, 1.0,0)) as TProfesional,
              sum(IIF(P_NIVEL_ANOSR = 8, 1.0,0)) as Universitario,
              sum(IIF(P_NIVEL_ANOSR = 9, 1.0,0)) as EspMaesDoc,
              sum(IIF(P_NIVEL_ANOSR = 10, 1.0,0)) as SinNE,
              sum(IIF(P_NIVEL_ANOSR = 99, 1.0,0)) as NSNR,
              sum(IIF(P_EST_CIVIL = 1, 1.0,0)) as UnionLibre,
              sum(IIF(P_EST_CIVIL = 2, 1.0,0)) as Casado,
              sum(IIF(P_EST_CIVIL = 3, 1.0,0)) as Divorciado,
              sum(IIF(P_EST_CIVIL = 4 OR P_EST_CIVIL = 5, 1.0,0)) as Separado,
              sum(IIF(P_EST_CIVIL = 6, 1.0,0)) as Viudo,
              sum(IIF(P_EST_CIVIL = 7, 1.0,0)) as Soltero,
              sum(IIF(P_EST_CIVIL = 9, 1.0,0)) as NSNR,
              sum(IIF(P_PARENTESCOR = 1, 1.0,0)) as JefeHogar,
              sum(IIF(P_PARENTESCOR = 2, 1.0,0)) as Pareja,
              sum(IIF(P_PARENTESCOR = 3, 1.0,0)) as Hijo,
              sum(IIF(P_PARENTESCOR = 4, 1.0,0)) as OParientes,
              sum(IIF(P_PARENTESCOR = 5, 1.0,0)) as NParientes,
              count(U_VIVIENDA) as Viviendas
           from Per_Mgn_Hog
           group by U_DPTO, U_MPIO,UA_CLASE
          "

#####TABLA PERSONA HOGAR Ejecuta la consulta SQL y guarda los resultados en tabla_PersonaHogar. Muestra la estructura de la tabla para verificar tipos de datos y contenido.

tabla_PersonaHogar es la siguiente:

Número de Observaciones: 11 Número de Variables: 71

Las variables más relevantes que se pueden sacar con respecto a la tabla de personas hogares son:

Identificadores: - U_DPTO: Código del departamento (numérico). - U_MPIO: Código del municipio (numérico). - UA_CLASE: Clasificación de área (numérico).

Indicadores por Edad y Sexo: - H_0_4, H_5_9, …, H_100_104: Cantidad de hombres en rangos de edad específicos. - M_0_4, M_5_9, …, M_100_104: Cantidad de mujeres en rangos de edad específicos.

Total de Hombres y Mujeres: Hombres: Total de hombres. Mujeres: Total de mujeres.

Nivel Educativo:

Prescolar, BPrimaria, BSecundaria, …, NSNR: Número de personas según su nivel educativo.

Estado Civil:

UnionLibre, Casado, Divorciado, Separado, Viudo, Soltero, NSNR: Cantidad de personas según su estado civil.

Rol en el Hogar:

JefeHogar, Pareja, Hijo, OParientes, NParientes: Cantidad de personas según su rol en el hogar.

Número de Viviendas:

Viviendas: Total de viviendas.

Cada fila en tabla_PersonaHogar representa un conjunto de datos agrupados por departamento (GUAINÍA), municipio y clasificación de área, con diversos indicadores demográficos .

tabla_PersonaHogar=sqldf(consulta_PersonaHogar)
str(tabla_PersonaHogar)
## 'data.frame':    11 obs. of  71 variables:
##  $ U_DPTO       : num  94 94 94 94 94 94 94 94 94 94 ...
##  $ U_MPIO       : chr  "001" "001" "001" "343" ...
##  $ UA_CLASE     : num  1 2 3 2 3 2 3 2 3 2 ...
##  $ H_00_04      : num  949 140 343 54 357 5 48 0 68 7 ...
##  $ H_05_09      : num  994 162 879 65 708 17 111 0 152 9 ...
##  $ H_10_14      : num  995 136 895 48 662 36 93 0 129 13 ...
##  $ H_15_19      : num  1062 116 685 55 555 ...
##  $ H_20_24      : num  1091 109 451 60 343 ...
##  $ H_25_29      : num  818 79 250 40 166 8 36 0 40 7 ...
##  $ H_30_34      : num  726 72 226 28 114 4 30 1 44 4 ...
##  $ H_35_39      : num  637 91 232 19 102 3 38 1 37 8 ...
##  $ H_40_44      : num  528 56 162 25 79 2 37 0 43 6 ...
##  $ H_45_49      : num  520 55 112 17 90 4 27 1 35 3 ...
##  $ H_50_54      : num  415 43 113 19 67 3 20 0 33 3 ...
##  $ H_55_59      : num  368 44 117 22 55 6 11 0 22 1 ...
##  $ H_60_64      : num  225 30 71 12 17 1 15 0 17 1 ...
##  $ H_65_69      : num  155 15 51 9 25 1 9 0 13 3 ...
##  $ H_70_74      : num  140 14 34 7 19 2 5 0 13 1 ...
##  $ H_75_79      : num  91 7 22 3 7 0 5 0 2 1 ...
##  $ H_80_84      : num  32 2 12 2 5 1 2 0 4 0 ...
##  $ H_85_89      : num  21 2 5 0 3 0 1 0 2 0 ...
##  $ H_90_94      : num  3 1 1 0 2 0 1 0 0 0 ...
##  $ H_95_99      : num  3 1 0 1 0 0 0 0 1 0 ...
##  $ H_100_104    : num  2 0 1 0 1 0 0 0 0 0 ...
##  $ M_00_04      : num  913 134 321 52 320 6 66 0 61 11 ...
##  $ M_05_09      : num  962 137 869 58 722 17 99 0 175 12 ...
##  $ M_10_14      : num  973 128 705 42 634 28 90 0 134 6 ...
##  $ M_15_19      : num  1002 152 555 53 386 ...
##  $ M_20_24      : num  978 104 263 54 212 4 41 2 53 3 ...
##  $ M_25_29      : num  852 100 223 39 143 10 37 2 45 8 ...
##  $ M_30_34      : num  725 64 184 26 110 3 37 0 36 4 ...
##  $ M_35_39      : num  711 70 143 22 90 7 20 0 39 5 ...
##  $ M_40_44      : num  593 40 140 24 81 5 25 1 30 3 ...
##  $ M_45_49      : num  495 45 87 13 68 2 23 0 36 2 ...
##  $ M_50_54      : num  425 38 100 17 46 2 22 0 18 1 ...
##  $ M_55_59      : num  326 25 96 15 42 3 10 0 14 4 ...
##  $ M_60_64      : num  200 20 40 2 15 1 12 0 11 1 ...
##  $ M_65_69      : num  153 12 42 4 19 0 6 0 16 4 ...
##  $ M_70_74      : num  105 11 33 1 16 0 5 0 14 1 ...
##  $ M_75_79      : num  81 9 22 4 7 0 3 0 8 0 ...
##  $ M_80_84      : num  30 4 12 0 4 2 1 0 2 0 ...
##  $ M_85_89      : num  18 0 5 0 2 0 1 0 2 0 ...
##  $ M_90_94      : num  8 0 1 0 1 0 1 0 0 0 ...
##  $ M_95_99      : num  1 2 3 0 0 0 0 0 0 0 ...
##  $ M_100_104    : num  0 1 1 0 0 0 0 0 2 0 ...
##  $ Hombres      : num  9775 1175 4662 486 3377 ...
##  $ Mujeres      : num  9551 1096 3845 426 2918 ...
##  $ Prescolar    : num  581 94 576 30 472 10 62 0 103 14 ...
##  $ BPrimaria    : num  6044 953 4125 314 2968 ...
##  $ BSecundaria  : num  3676 428 1583 170 1157 ...
##  $ MAcademica   : num  2408 147 318 98 276 ...
##  $ MTecnica     : num  320 24 34 49 51 2 16 0 21 0 ...
##  $ Normalista   : num  64 4 16 8 8 1 1 0 8 0 ...
##  $ TProfesional : num  1455 36 141 25 25 ...
##  $ Universitario: num  947 18 68 30 33 4 4 0 4 2 ...
##  $ EspMaesDoc   : num  404 4 18 8 18 2 2 0 1 0 ...
##  $ SinNE        : num  1017 148 598 19 275 ...
##  $ NSNR         : num  548 141 366 55 335 17 64 8 127 8 ...
##  $ UnionLibre   : num  5800 565 1661 236 1161 ...
##  $ Casado       : num  1582 303 745 70 219 ...
##  $ Divorciado   : num  42 1 8 0 1 2 4 1 4 0 ...
##  $ Separado     : num  816 44 109 29 79 7 6 1 20 4 ...
##  $ Viudo        : num  363 40 113 8 60 2 19 0 35 1 ...
##  $ Soltero      : num  6442 643 1559 276 1094 ...
##  $ NSNR         : num  463 102 1900 64 1574 ...
##  $ JefeHogar    : num  5575 554 1542 226 793 ...
##  $ Pareja       : num  3106 396 1095 135 628 ...
##  $ Hijo         : num  7946 1080 2603 416 2307 ...
##  $ OParientes   : num  2270 223 395 131 496 10 100 0 94 28 ...
##  $ NParientes   : num  180 18 19 4 20 1 2 2 4 3 ...
##  $ Viviendas    : int  19326 2271 8507 912 6295 249 1162 11 1632 152 ...

Muestra los nombres de las columnas. Renombra la columna 65 como “NSNR2”.

colnames(tabla_PersonaHogar)
##  [1] "U_DPTO"        "U_MPIO"        "UA_CLASE"      "H_00_04"      
##  [5] "H_05_09"       "H_10_14"       "H_15_19"       "H_20_24"      
##  [9] "H_25_29"       "H_30_34"       "H_35_39"       "H_40_44"      
## [13] "H_45_49"       "H_50_54"       "H_55_59"       "H_60_64"      
## [17] "H_65_69"       "H_70_74"       "H_75_79"       "H_80_84"      
## [21] "H_85_89"       "H_90_94"       "H_95_99"       "H_100_104"    
## [25] "M_00_04"       "M_05_09"       "M_10_14"       "M_15_19"      
## [29] "M_20_24"       "M_25_29"       "M_30_34"       "M_35_39"      
## [33] "M_40_44"       "M_45_49"       "M_50_54"       "M_55_59"      
## [37] "M_60_64"       "M_65_69"       "M_70_74"       "M_75_79"      
## [41] "M_80_84"       "M_85_89"       "M_90_94"       "M_95_99"      
## [45] "M_100_104"     "Hombres"       "Mujeres"       "Prescolar"    
## [49] "BPrimaria"     "BSecundaria"   "MAcademica"    "MTecnica"     
## [53] "Normalista"    "TProfesional"  "Universitario" "EspMaesDoc"   
## [57] "SinNE"         "NSNR"          "UnionLibre"    "Casado"       
## [61] "Divorciado"    "Separado"      "Viudo"         "Soltero"      
## [65] "NSNR"          "JefeHogar"     "Pareja"        "Hijo"         
## [69] "OParientes"    "NParientes"    "Viviendas"
colnames(tabla_PersonaHogar)[65] <- "NSNR2"
Cálculo de Indicadores Demográficos y Resultados

Cálculos demográficos:

Se calculan indicadores clave como el total de población, desglosado por sexo y rangos de edad. Se calculan índices demográficos, como el porcentaje de ancianos, el índice de envejecimiento, el índice de feminización, la relación de dependencia de vejez, entre otros. Resultados en tabla:

Los resultados de los cálculos se organizan en una tabla que incluye indicadores como la relación de masculinidad y la dependencia juvenil, proporcionando una vista resumida de los datos demográficos.

# Total de población (hombres + mujeres)
total_poblacion <- tabla_PersonaHogar %>%
  summarise(Total_Poblacion = sum(Hombres + Mujeres))

# Total de población hombres +60
total_hombres_mas_60 <- tabla_PersonaHogar %>%
  summarise(Total_Hombres_Mas_60 = sum(H_60_64 + H_65_69 + H_70_74 + H_75_79 + H_80_84 + H_85_89 + H_90_94 + H_95_99 + H_100_104))

# Total de población hombres +80
total_hombres_mas_80 <- tabla_PersonaHogar %>%
  summarise(Total_Hombres_Mas_80 = sum(H_80_84 + H_85_89 + H_90_94 + H_95_99 + H_100_104))

# Total de población hombres entre 0 y 14
total_hombres_0_14 <- tabla_PersonaHogar %>%
  summarise(Total_Hombres_0_14 = sum(H_00_04 + H_05_09 + H_10_14))

# Total de población hombres entre 15 y 59
total_hombres_15_59 <- tabla_PersonaHogar %>%
  summarise(Total_Hombres_15_59 = sum(H_15_19 + H_20_24 + H_25_29 + H_30_34 + H_35_39 + H_40_44 + H_45_49 + H_50_54 + H_55_59))

# Total de población mujeres +60
total_mujeres_mas_60 <- tabla_PersonaHogar %>%
  summarise(Total_Mujeres_Mas_60 = sum(M_60_64 + M_65_69 + M_70_74 + M_75_79 + M_80_84 + M_85_89 + M_90_94 + M_95_99 + M_100_104))

# Total de población mujeres +80
total_mujeres_mas_80 <- tabla_PersonaHogar %>%
  summarise(Total_Mujeres_Mas_80 = sum(M_80_84 + M_85_89 + M_90_94 + M_95_99 + M_100_104))

# Total de población mujeres entre 0 y 14
total_mujeres_0_14 <- tabla_PersonaHogar %>%
  summarise(Total_Mujeres_0_14 = sum(M_00_04 + M_05_09 + M_10_14))

# Total de población mujeres entre 15 y 59
total_mujeres_15_59 <- tabla_PersonaHogar %>%
  summarise(Total_Mujeres_15_59 = sum(M_15_19 + M_20_24 + M_25_29 + M_30_34 + M_35_39 + M_40_44 + M_45_49 + M_50_54 + M_55_59))

# Total de población hombres
total_hombres <- tabla_PersonaHogar %>%
  summarise(Total_Hombres = sum(Hombres))

# Total de población mujeres
total_mujeres <- tabla_PersonaHogar %>%
  summarise(Total_Mujeres = sum(Mujeres))

# Calculando indicadores demográficos
# Porcentaje de ancianos (+60)
porcentaje_ancianos <- (total_hombres_mas_60$Total_Hombres_Mas_60 + total_mujeres_mas_60$Total_Mujeres_Mas_60) / total_poblacion$Total_Poblacion * 100

# Índice de envejecimiento (Población +60 / Población 0-14)
indice_envejecimiento <- (total_hombres_mas_60$Total_Hombres_Mas_60 + total_mujeres_mas_60$Total_Mujeres_Mas_60) / (total_hombres_0_14$Total_Hombres_0_14 + total_mujeres_0_14$Total_Mujeres_0_14)*100

# Índice de sobreenvejecimiento (Población +80 / Población +60)
indice_sobreenvejecimiento <- (total_hombres_mas_80$Total_Hombres_Mas_80 + total_mujeres_mas_80$Total_Mujeres_Mas_80) / (total_hombres_mas_60$Total_Hombres_Mas_60 + total_mujeres_mas_60$Total_Mujeres_Mas_60)*100

# Índice de feminización (Población de mujeres +60 / Población de hombres +60)
indice_feminizacion <- (total_mujeres_mas_60$Total_Mujeres_Mas_60 / total_hombres_mas_60$Total_Hombres_Mas_60)*100

# Relación de dependencia de vejez ((Población +60 / Población 15-59) * 100)
relacion_dependencia_vejez <- (total_hombres_mas_60$Total_Hombres_Mas_60 + total_mujeres_mas_60$Total_Mujeres_Mas_60) / (total_hombres_15_59$Total_Hombres_15_59 + total_mujeres_15_59$Total_Mujeres_15_59) * 100

# Índice de dependencia ((Población 0-14 + Población +60) / Población 15-59)
indice_dependencia <- (total_hombres_0_14$Total_Hombres_0_14 + total_mujeres_0_14$Total_Mujeres_0_14 + total_hombres_mas_60$Total_Hombres_Mas_60 + total_mujeres_mas_60$Total_Mujeres_Mas_60) / (total_hombres_15_59$Total_Hombres_15_59 + total_mujeres_15_59$Total_Mujeres_15_59)*100

# Total de población juvenil (0-14)
total_juvenil_0_14 <- tabla_PersonaHogar %>%
  summarise(Total_Juvenil_0_14 = sum(H_00_04 + H_05_09 + H_10_14 + M_00_04 + M_05_09 + M_10_14))

# Índice de dependencia juvenil ((Población 0-14 / Población 15-59) * 100)
indice_dependencia_juvenil<-(total_juvenil_0_14$Total_Juvenil_0_14) / (total_hombres_15_59$Total_Hombres_15_59+total_mujeres_15_59$Total_Mujeres_15_59) * 100

# Relación de masculinidad (Población de hombres / Población de mujeres)
relacion_masculinidad <- (total_hombres$Total_Hombres / total_mujeres$Total_Mujeres)*100

# Relación de femenina (Población de mujeres / Población de hombres)
relacion_femenina <- (total_mujeres$Total_Mujeres /total_hombres$Total_Hombres )*100
Resultados

Este código realiza lo siguiente:

Cálculos demográficos: Suma la población total por grupos de edad y sexo, y calcula índices importantes como envejecimiento y dependencia.

Creación de tabla: Organiza estos cálculos en una tabla (data.frame).

Reorganización: La tabla se coloca en formato vertical para que cada indicador esté en una fila, facilitando su lectura.

Formateo y visualización: Usa librerías para darle un estilo visual atractivo a la tabla, ideal para informes o presentaciones.

resultados <- data.frame(
  Total_Poblacion = total_poblacion$Total_Poblacion,
  Total_Hombres_Mas_60 = total_hombres_mas_60$Total_Hombres_Mas_60,
  Total_Hombres_Mas_80 = total_hombres_mas_80$Total_Hombres_Mas_80,
  Total_Hombres_0_14 = total_hombres_0_14$Total_Hombres_0_14,
  Total_Hombres_15_59 = total_hombres_15_59$Total_Hombres_15_59,
  Total_Mujeres_Mas_60 = total_mujeres_mas_60$Total_Mujeres_Mas_60,
  Total_Mujeres_Mas_80 = total_mujeres_mas_80$Total_Mujeres_Mas_80,
  Total_Mujeres_0_14 = total_mujeres_0_14$Total_Mujeres_0_14,
  Total_Mujeres_15_59 = total_mujeres_15_59$Total_Mujeres_15_59,
  Porcentaje_Ancianos = porcentaje_ancianos,
  Indice_Envejecimiento = indice_envejecimiento,
  Indice_Sobreenvejecimiento = indice_sobreenvejecimiento,
  Indice_Feminizacion = indice_feminizacion,
  Relacion_Dependencia_Vejez = relacion_dependencia_vejez,
  Indice_Dependencia = indice_dependencia,
  Relacion_Masculinidad = relacion_masculinidad,
  Relacion_Femenina = relacion_femenina,
  Indice_Dependencia_Juvenil = indice_dependencia_juvenil
)

library(knitr)
library(kableExtra)

# Transponer la tabla de resultados para que quede en formato vertical
resultados_transpuestos <- as.data.frame(t(resultados))

# Crear la tabla de resultados formateada
tabla_resultados <- resultados_transpuestos %>%
  kable(format = "html", caption = "Tabla de Resultados Demográficos (Transpuesta)") %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"), 
                full_width = F, 
                position = "center") %>%
  row_spec(0, bold = T, color = "white", background = "#4CAF50")  # Personalización del encabezado

# Mostrar la tabla
print(tabla_resultados)
## <table class="table table-striped table-hover table-condensed table-responsive" style="width: auto !important; margin-left: auto; margin-right: auto;">
## <caption>Tabla de Resultados Demográficos (Transpuesta)</caption>
##  <thead>
##   <tr>
##    <th style="text-align:left;font-weight: bold;color: white !important;background-color: rgba(76, 175, 80, 255) !important;">   </th>
##    <th style="text-align:right;font-weight: bold;color: white !important;background-color: rgba(76, 175, 80, 255) !important;"> V1 </th>
##   </tr>
##  </thead>
## <tbody>
##   <tr>
##    <td style="text-align:left;"> Total_Poblacion </td>
##    <td style="text-align:right;"> 41177.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Hombres_Mas_60 </td>
##    <td style="text-align:right;"> 1167.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Hombres_Mas_80 </td>
##    <td style="text-align:right;"> 114.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Hombres_0_14 </td>
##    <td style="text-align:right;"> 8219.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Hombres_15_59 </td>
##    <td style="text-align:right;"> 12108.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Mujeres_Mas_60 </td>
##    <td style="text-align:right;"> 994.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Mujeres_Mas_80 </td>
##    <td style="text-align:right;"> 107.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Mujeres_0_14 </td>
##    <td style="text-align:right;"> 7836.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Total_Mujeres_15_59 </td>
##    <td style="text-align:right;"> 10853.000000 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Porcentaje_Ancianos </td>
##    <td style="text-align:right;"> 5.248075 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Indice_Envejecimiento </td>
##    <td style="text-align:right;"> 13.459981 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Indice_Sobreenvejecimiento </td>
##    <td style="text-align:right;"> 10.226747 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Indice_Feminizacion </td>
##    <td style="text-align:right;"> 85.175664 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Relacion_Dependencia_Vejez </td>
##    <td style="text-align:right;"> 9.411611 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Indice_Dependencia </td>
##    <td style="text-align:right;"> 79.334524 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Relacion_Masculinidad </td>
##    <td style="text-align:right;"> 109.200833 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Relacion_Femenina </td>
##    <td style="text-align:right;"> 91.574393 </td>
##   </tr>
##   <tr>
##    <td style="text-align:left;"> Indice_Dependencia_Juvenil </td>
##    <td style="text-align:right;"> 69.922913 </td>
##   </tr>
## </tbody>
## </table>

Porcentaje de Anciano: El 5.24% de la población de GUAINÍA tiene 60 años o más. Podemos suponer que la población de Guainía es realtivamente joven.

Índice de Envejecimiento: Con un índice de envejecimiento de 13.45%, hay aproximadamente 13 ancianos por cada 100 jóvenes. Esto indica una carga baja de los ancianos sobre la población joven.

Índice de Sobreenvejecimiento: El 10.23% de la población de 60 años o más tiene 80 años o más. Esto muestra que una parte significativa pero moderada de los ancianos está en una etapa avanzada de vejez, lo que puede requerir atención y servicios específicos.

Índice de Feminización: El índice de feminización en la población de 60 años o más es del 85.18%, lo que indica que hay más mujeres que hombres en este grupo etario.

Relación de Dependencia de Vejez: La relación de dependencia de vejez es del 9.4%%, lo que significa que hay aproximadamente 9 ancianos por cada 100 personas en edad económicamente activa, lo que indica quer la carga de de los ancianos sobre esta última población, es baja.

Índice de Dependencia: Con un índice de dependencia de 79.3%, hay aproximadamente 79 personas (jóvenes y ancianos) que dependen de cada 100 personas en edad laboral. Esto sugiere una carga moderada en términos de dependencia sobre la población econímicamente activa.

Relación de Masculinidad: La relación de masculinidad es de 109.2, lo que significa que hay 109 hombres por cada 100 mujeres en la población total. Esto indíca que en la población del departamento de Guainía predomina la presencia de los hombres.

Relación Femenina: Con una relación femenina de 91.6%, hay aproximadamente 92 mujeres por cada 100 hombres. Lo que podemos contrastar con el indicador anterior, donde pese a que la presencia de hombres es mayor, no es una diferencia significativa.

El Índice de Dependencia Juvenil: El 69.9%% indica que por cada 100 personas en edad de trabajar, hay aproximadamente 70 jóvenes que dependen de ellos. Este valor sugiere una estructura demográfica relativamente joven, donde podemos sugerir que se debe generar mayor inversión enfocada al desarrollo y bienestar de los jovenes de este departamento.

#####PORCENTAJE DE CABECERAS URBANAS

Cálculo de población total:

Suma el total de hombres y mujeres de la tabla tabla_PersonaHogar y los almacena en total_poblacional. Cálculo de población en cabecera urbana:

Filtra los datos para obtener solo la población de áreas urbanas (donde UA_CLASE == 1), y luego suma hombres y mujeres de esas zonas en poblacion_cabecera_urbana. Cálculo de totales:

Se calcula el total de personas en cabeceras urbanas (total_cabecera_urbana) y el total general de la población (poblacion_total). Porcentaje de población urbana:

Se calcula el porcentaje de personas que viven en cabeceras urbanas respecto al total de la población, y se imprime el resultado.

total_poblacional <- tabla_PersonaHogar %>%
  summarise(Total_Hombres = sum(Hombres), Total_Mujeres = sum(Mujeres))

poblacion_cabecera_urbana <- tabla_PersonaHogar %>%
  filter(UA_CLASE == 1) %>%
  summarise(Total_Hombres = sum(Hombres), Total_Mujeres = sum(Mujeres))

total_cabecera_urbana <- sum(poblacion_cabecera_urbana$Total_Hombres + poblacion_cabecera_urbana$Total_Mujeres)
poblacion_total <- sum(total_poblacional$Total_Hombres + total_poblacional$Total_Mujeres)

porcentaje_cabecera_urbana <- (total_cabecera_urbana / poblacion_total) * 100
print(paste("El porcentaje de población en Cabeceras Urbanas es:", porcentaje_cabecera_urbana))
## [1] "El porcentaje de población en Cabeceras Urbanas es: 46.9339679918401"

Este resultado sugiere que la población en el área urbana es significativa, con casi la mitad de la población ubicada en la cabecera urbana.

Porcentaje de Población en Centros Poblados

Calcula la población en centros poblados: Filtra la población de centros poblados y suma hombres y mujeres.

Suma total de la población en centros poblados: Suma el total de personas en estos centros.

Calcula el porcentaje: Calcula qué porcentaje de la población total vive en centros poblados.

Muestra el porcentaje: Imprime el porcentaje de personas que viven en centros poblados.

poblacion_centros_poblados <- tabla_PersonaHogar %>%
  filter(UA_CLASE == 2) %>%
  summarise(across(starts_with("H_"), sum), 
            across(starts_with("M_"), sum))

total_centros_poblados <- sum(poblacion_centros_poblados)

porcentaje_centros_poblados <- (total_centros_poblados / poblacion_total) * 100

# Mostrar el resultado
porcentaje_centros_poblados
## [1] 8.730602

Este resultado 8.73 que una parte muy pequeña de la población ha decidido vivir en los centros poblados, lo que a comparación de la población ubicada en las cabeceras urbana, es baja.

Porcentaje de Población en Áreas Rurales Dispersas

Calcula la población en áreas rurales dispersas: Filtra los datos para obtener la población en áreas rurales dispersas (donde UA_CLASE == 3), y suma las columnas que contienen la población de hombres y mujeres.

Suma total de la población en áreas rurales dispersas: Calcula el total de personas que viven en estas zonas.

Calcula el porcentaje: Determina qué porcentaje de la población total vive en áreas rurales dispersas.

Muestra el porcentaje: Imprime el porcentaje de personas que viven en áreas rurales dispersas.

poblacion_rural_disperso <- tabla_PersonaHogar %>%
  filter(UA_CLASE == 3) %>%
  summarise(across(starts_with("H_"), sum), 
            across(starts_with("M_"), sum))

total_rural_disperso <- sum(poblacion_rural_disperso)

porcentaje_rural_disperso <- (total_rural_disperso / poblacion_total) * 100

# Mostrar el resultado
porcentaje_rural_disperso
## [1] 44.33543

La población ubicada en las áreas rurales dispersas es de 44.3 lo que demuestra que casi la mitad de la población del municipio de Guainía esta proporcionalmente distribuida entre los diferentes centros rurales y urbanos, sin embargo, es necesario tener en cuenta el área que conforma el departamento para establecer si la población se encuentra uniformemente distribuida en el departamento, y así establecer políticas públicas a favor de la población.

Densidad Poblacional

Define el área en km²: Se establece que el área total es de 72,238 km².

Calcula la densidad poblacional: Divide la población total entre el área para obtener la densidad poblacional (personas por km²).

Muestra la densidad poblacional: Imprime el resultado de la densidad poblacional.

area_ET_km2 <- 72238 

# Calcular la densidad poblacional (población total / área en km²)
densidad_poblacional <- poblacion_total / area_ET_km2

# Mostrar el resultado
densidad_poblacional
## [1] 0.5700185

Densidad poblacional = 0.57 habitantes/km² significa que, en promedio, menos de una persona habita por cada kilómetro cuadrado en el departamento de Guainía. Este valor indica una densidad poblacional extremadamente baja, esto suele suceder en áreas rurales, selváticas o poco desarrolladas, como es el caso de Guainía, que es un departamento caracterizado por grandes extensiones de territorio y baja población.

#####PIRÁMIDE POBLACIONAL Este código realiza un análisis detallado de la población y la organiza en una pirámide poblacional, presentando los resultados por grupos de edad (quinquenios) y sexo (hombres y mujeres). A continuación te explico cada parte de forma simple:

Selección de columnas: Se seleccionan las columnas necesarias del dataframe tabla_PersonaHogar y se filtran las filas donde UA_CLASE es 1, 2 o 3, que corresponden a diferentes áreas de población (urbana, centros poblados y rural).

Eliminación y reestructuración de columnas: Se eliminan columnas innecesarias y se reorganiza el dataframe en formato largo, lo que facilita el manejo de los datos, con la creación de nuevas columnas para clasificar por sexo y grupo de edad.

Agrupación y suma de la población: Los datos se agrupan por quinquenios y sexo, sumando la población correspondiente a cada grupo de edad y sexo.

Reorganización y conversión de datos: Se reestructura el dataframe para separar hombres y mujeres en columnas diferentes y se calcula la población total por quinquenios.

Cálculo de proporciones: Se calcula el porcentaje de población de hombres y mujeres respecto al total, pero sin multiplicar por 100 (en proporciones).

Creación de la pirámide poblacional: Se utiliza ggplot para crear un gráfico de pirámide poblacional que muestra la proporción de hombres y mujeres por quinquenio, con los hombres representados en valores negativos para hacer más visual la comparación.

Estilo y presentación: El gráfico se ajusta para mostrar una pirámide horizontal, con etiquetas y formato personalizado, mostrando claramente la distribución de la población por edad y sexo.

# Seleccionar columnas de la 2 a la 45
poblacion_comb <- tabla_PersonaHogar[, 2:45]  
print(poblacion_comb)  # Verifica el dataframe
##    U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1     001        1     949     994     995    1062    1091     818     726
## 2     001        2     140     162     136     116     109      79      72
## 3     001        3     343     879     895     685     451     250     226
## 4     343        2      54      65      48      55      60      40      28
## 5     343        3     357     708     662     555     343     166     114
## 6     883        2       5      17      36      33      12       8       4
## 7     883        3      48     111      93      59      49      36      30
## 8     884        2       0       0       0       0       2       0       1
## 9     884        3      68     152     129     148      54      40      44
## 10    888        2       7       9      13       8       7       7       4
## 11    888        3      33      58      53      59      31      16      22
##    H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1      637     528     520     415     368     225     155     140      91
## 2       91      56      55      43      44      30      15      14       7
## 3      232     162     112     113     117      71      51      34      22
## 4       19      25      17      19      22      12       9       7       3
## 5      102      79      90      67      55      17      25      19       7
## 6        3       2       4       3       6       1       1       2       0
## 7       38      37      27      20      11      15       9       5       5
## 8        1       0       1       0       0       0       0       0       0
## 9       37      43      35      33      22      17      13      13       2
## 10       8       6       3       3       1       1       3       1       1
## 11      13      13       6      13      11       3       2       2       3
##    H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1       32      21       3       3         2     913     962     973    1002
## 2        2       2       1       1         0     134     137     128     152
## 3       12       5       1       0         1     321     869     705     555
## 4        2       0       0       1         0      52      58      42      53
## 5        5       3       2       0         1     320     722     634     386
## 6        1       0       0       0         0       6      17      28      21
## 7        2       1       1       0         0      66      99      90      66
## 8        0       0       0       0         0       0       0       0       1
## 9        4       2       0       1         0      61     175     134      79
## 10       0       0       0       0         0      11      12       6       5
## 11       1       1       0       0         0      35      57      69      40
##    M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1      978     852     725     711     593     495     425     326     200
## 2      104     100      64      70      40      45      38      25      20
## 3      263     223     184     143     140      87     100      96      40
## 4       54      39      26      22      24      13      17      15       2
## 5      212     143     110      90      81      68      46      42      15
## 6        4      10       3       7       5       2       2       3       1
## 7       41      37      37      20      25      23      22      10      12
## 8        2       2       0       0       1       0       0       0       0
## 9       53      45      36      39      30      36      18      14      11
## 10       3       8       4       5       3       2       1       4       1
## 11      30      17      15      17      14       1       9       4       2
##    M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      153     105      81      30      18       8       1         0
## 2       12      11       9       4       0       0       2         1
## 3       42      33      22      12       5       1       3         1
## 4        4       1       4       0       0       0       0         0
## 5       19      16       7       4       2       1       0         0
## 6        0       0       0       2       0       0       0         0
## 7        6       5       3       1       1       1       0         0
## 8        0       0       0       0       0       0       0         0
## 9       16      14       8       2       2       0       0         2
## 10       4       1       0       0       0       0       0         0
## 11       3       4       0       1       1       0       1         0
# Filtrar solo donde UA_CLASE es 1, 2 o 3 (Centros Municipales, Menores y Otros)
poblacion_comb <- poblacion_comb %>%
  filter(UA_CLASE %in% c(1, 2, 3))  
print(poblacion_comb)  # Verifica los datos después de filtrar
##    U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1     001        1     949     994     995    1062    1091     818     726
## 2     001        2     140     162     136     116     109      79      72
## 3     001        3     343     879     895     685     451     250     226
## 4     343        2      54      65      48      55      60      40      28
## 5     343        3     357     708     662     555     343     166     114
## 6     883        2       5      17      36      33      12       8       4
## 7     883        3      48     111      93      59      49      36      30
## 8     884        2       0       0       0       0       2       0       1
## 9     884        3      68     152     129     148      54      40      44
## 10    888        2       7       9      13       8       7       7       4
## 11    888        3      33      58      53      59      31      16      22
##    H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1      637     528     520     415     368     225     155     140      91
## 2       91      56      55      43      44      30      15      14       7
## 3      232     162     112     113     117      71      51      34      22
## 4       19      25      17      19      22      12       9       7       3
## 5      102      79      90      67      55      17      25      19       7
## 6        3       2       4       3       6       1       1       2       0
## 7       38      37      27      20      11      15       9       5       5
## 8        1       0       1       0       0       0       0       0       0
## 9       37      43      35      33      22      17      13      13       2
## 10       8       6       3       3       1       1       3       1       1
## 11      13      13       6      13      11       3       2       2       3
##    H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1       32      21       3       3         2     913     962     973    1002
## 2        2       2       1       1         0     134     137     128     152
## 3       12       5       1       0         1     321     869     705     555
## 4        2       0       0       1         0      52      58      42      53
## 5        5       3       2       0         1     320     722     634     386
## 6        1       0       0       0         0       6      17      28      21
## 7        2       1       1       0         0      66      99      90      66
## 8        0       0       0       0         0       0       0       0       1
## 9        4       2       0       1         0      61     175     134      79
## 10       0       0       0       0         0      11      12       6       5
## 11       1       1       0       0         0      35      57      69      40
##    M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1      978     852     725     711     593     495     425     326     200
## 2      104     100      64      70      40      45      38      25      20
## 3      263     223     184     143     140      87     100      96      40
## 4       54      39      26      22      24      13      17      15       2
## 5      212     143     110      90      81      68      46      42      15
## 6        4      10       3       7       5       2       2       3       1
## 7       41      37      37      20      25      23      22      10      12
## 8        2       2       0       0       1       0       0       0       0
## 9       53      45      36      39      30      36      18      14      11
## 10       3       8       4       5       3       2       1       4       1
## 11      30      17      15      17      14       1       9       4       2
##    M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      153     105      81      30      18       8       1         0
## 2       12      11       9       4       0       0       2         1
## 3       42      33      22      12       5       1       3         1
## 4        4       1       4       0       0       0       0         0
## 5       19      16       7       4       2       1       0         0
## 6        0       0       0       2       0       0       0         0
## 7        6       5       3       1       1       1       0         0
## 8        0       0       0       0       0       0       0         0
## 9       16      14       8       2       2       0       0         2
## 10       4       1       0       0       0       0       0         0
## 11       3       4       0       1       1       0       1         0
# Eliminar la segunda columna
poblacion_comb <- poblacion_comb[,-c(2)]  
print(poblacion_comb)  # Verifica el dataframe sin la columna
##    U_MPIO H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34 H_35_39
## 1     001     949     994     995    1062    1091     818     726     637
## 2     001     140     162     136     116     109      79      72      91
## 3     001     343     879     895     685     451     250     226     232
## 4     343      54      65      48      55      60      40      28      19
## 5     343     357     708     662     555     343     166     114     102
## 6     883       5      17      36      33      12       8       4       3
## 7     883      48     111      93      59      49      36      30      38
## 8     884       0       0       0       0       2       0       1       1
## 9     884      68     152     129     148      54      40      44      37
## 10    888       7       9      13       8       7       7       4       8
## 11    888      33      58      53      59      31      16      22      13
##    H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79 H_80_84
## 1      528     520     415     368     225     155     140      91      32
## 2       56      55      43      44      30      15      14       7       2
## 3      162     112     113     117      71      51      34      22      12
## 4       25      17      19      22      12       9       7       3       2
## 5       79      90      67      55      17      25      19       7       5
## 6        2       4       3       6       1       1       2       0       1
## 7       37      27      20      11      15       9       5       5       2
## 8        0       1       0       0       0       0       0       0       0
## 9       43      35      33      22      17      13      13       2       4
## 10       6       3       3       1       1       3       1       1       0
## 11      13       6      13      11       3       2       2       3       1
##    H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19 M_20_24
## 1       21       3       3         2     913     962     973    1002     978
## 2        2       1       1         0     134     137     128     152     104
## 3        5       1       0         1     321     869     705     555     263
## 4        0       0       1         0      52      58      42      53      54
## 5        3       2       0         1     320     722     634     386     212
## 6        0       0       0         0       6      17      28      21       4
## 7        1       1       0         0      66      99      90      66      41
## 8        0       0       0         0       0       0       0       1       2
## 9        2       0       1         0      61     175     134      79      53
## 10       0       0       0         0      11      12       6       5       3
## 11       1       0       0         0      35      57      69      40      30
##    M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64 M_65_69
## 1      852     725     711     593     495     425     326     200     153
## 2      100      64      70      40      45      38      25      20      12
## 3      223     184     143     140      87     100      96      40      42
## 4       39      26      22      24      13      17      15       2       4
## 5      143     110      90      81      68      46      42      15      19
## 6       10       3       7       5       2       2       3       1       0
## 7       37      37      20      25      23      22      10      12       6
## 8        2       0       0       1       0       0       0       0       0
## 9       45      36      39      30      36      18      14      11      16
## 10       8       4       5       3       2       1       4       1       4
## 11      17      15      17      14       1       9       4       2       3
##    M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      105      81      30      18       8       1         0
## 2       11       9       4       0       0       2         1
## 3       33      22      12       5       1       3         1
## 4        1       4       0       0       0       0         0
## 5       16       7       4       2       1       0         0
## 6        0       0       2       0       0       0         0
## 7        5       3       1       1       1       0         0
## 8        0       0       0       0       0       0         0
## 9       14       8       2       2       0       0         2
## 10       1       0       0       0       0       0         0
## 11       4       0       1       1       0       1         0
# Convertir el dataframe a formato largo
poblacion_comb <- melt(poblacion_comb, id.vars = "U_MPIO")  
print(poblacion_comb)
##     U_MPIO  variable value
## 1      001   H_00_04   949
## 2      001   H_00_04   140
## 3      001   H_00_04   343
## 4      343   H_00_04    54
## 5      343   H_00_04   357
## 6      883   H_00_04     5
## 7      883   H_00_04    48
## 8      884   H_00_04     0
## 9      884   H_00_04    68
## 10     888   H_00_04     7
## 11     888   H_00_04    33
## 12     001   H_05_09   994
## 13     001   H_05_09   162
## 14     001   H_05_09   879
## 15     343   H_05_09    65
## 16     343   H_05_09   708
## 17     883   H_05_09    17
## 18     883   H_05_09   111
## 19     884   H_05_09     0
## 20     884   H_05_09   152
## 21     888   H_05_09     9
## 22     888   H_05_09    58
## 23     001   H_10_14   995
## 24     001   H_10_14   136
## 25     001   H_10_14   895
## 26     343   H_10_14    48
## 27     343   H_10_14   662
## 28     883   H_10_14    36
## 29     883   H_10_14    93
## 30     884   H_10_14     0
## 31     884   H_10_14   129
## 32     888   H_10_14    13
## 33     888   H_10_14    53
## 34     001   H_15_19  1062
## 35     001   H_15_19   116
## 36     001   H_15_19   685
## 37     343   H_15_19    55
## 38     343   H_15_19   555
## 39     883   H_15_19    33
## 40     883   H_15_19    59
## 41     884   H_15_19     0
## 42     884   H_15_19   148
## 43     888   H_15_19     8
## 44     888   H_15_19    59
## 45     001   H_20_24  1091
## 46     001   H_20_24   109
## 47     001   H_20_24   451
## 48     343   H_20_24    60
## 49     343   H_20_24   343
## 50     883   H_20_24    12
## 51     883   H_20_24    49
## 52     884   H_20_24     2
## 53     884   H_20_24    54
## 54     888   H_20_24     7
## 55     888   H_20_24    31
## 56     001   H_25_29   818
## 57     001   H_25_29    79
## 58     001   H_25_29   250
## 59     343   H_25_29    40
## 60     343   H_25_29   166
## 61     883   H_25_29     8
## 62     883   H_25_29    36
## 63     884   H_25_29     0
## 64     884   H_25_29    40
## 65     888   H_25_29     7
## 66     888   H_25_29    16
## 67     001   H_30_34   726
## 68     001   H_30_34    72
## 69     001   H_30_34   226
## 70     343   H_30_34    28
## 71     343   H_30_34   114
## 72     883   H_30_34     4
## 73     883   H_30_34    30
## 74     884   H_30_34     1
## 75     884   H_30_34    44
## 76     888   H_30_34     4
## 77     888   H_30_34    22
## 78     001   H_35_39   637
## 79     001   H_35_39    91
## 80     001   H_35_39   232
## 81     343   H_35_39    19
## 82     343   H_35_39   102
## 83     883   H_35_39     3
## 84     883   H_35_39    38
## 85     884   H_35_39     1
## 86     884   H_35_39    37
## 87     888   H_35_39     8
## 88     888   H_35_39    13
## 89     001   H_40_44   528
## 90     001   H_40_44    56
## 91     001   H_40_44   162
## 92     343   H_40_44    25
## 93     343   H_40_44    79
## 94     883   H_40_44     2
## 95     883   H_40_44    37
## 96     884   H_40_44     0
## 97     884   H_40_44    43
## 98     888   H_40_44     6
## 99     888   H_40_44    13
## 100    001   H_45_49   520
## 101    001   H_45_49    55
## 102    001   H_45_49   112
## 103    343   H_45_49    17
## 104    343   H_45_49    90
## 105    883   H_45_49     4
## 106    883   H_45_49    27
## 107    884   H_45_49     1
## 108    884   H_45_49    35
## 109    888   H_45_49     3
## 110    888   H_45_49     6
## 111    001   H_50_54   415
## 112    001   H_50_54    43
## 113    001   H_50_54   113
## 114    343   H_50_54    19
## 115    343   H_50_54    67
## 116    883   H_50_54     3
## 117    883   H_50_54    20
## 118    884   H_50_54     0
## 119    884   H_50_54    33
## 120    888   H_50_54     3
## 121    888   H_50_54    13
## 122    001   H_55_59   368
## 123    001   H_55_59    44
## 124    001   H_55_59   117
## 125    343   H_55_59    22
## 126    343   H_55_59    55
## 127    883   H_55_59     6
## 128    883   H_55_59    11
## 129    884   H_55_59     0
## 130    884   H_55_59    22
## 131    888   H_55_59     1
## 132    888   H_55_59    11
## 133    001   H_60_64   225
## 134    001   H_60_64    30
## 135    001   H_60_64    71
## 136    343   H_60_64    12
## 137    343   H_60_64    17
## 138    883   H_60_64     1
## 139    883   H_60_64    15
## 140    884   H_60_64     0
## 141    884   H_60_64    17
## 142    888   H_60_64     1
## 143    888   H_60_64     3
## 144    001   H_65_69   155
## 145    001   H_65_69    15
## 146    001   H_65_69    51
## 147    343   H_65_69     9
## 148    343   H_65_69    25
## 149    883   H_65_69     1
## 150    883   H_65_69     9
## 151    884   H_65_69     0
## 152    884   H_65_69    13
## 153    888   H_65_69     3
## 154    888   H_65_69     2
## 155    001   H_70_74   140
## 156    001   H_70_74    14
## 157    001   H_70_74    34
## 158    343   H_70_74     7
## 159    343   H_70_74    19
## 160    883   H_70_74     2
## 161    883   H_70_74     5
## 162    884   H_70_74     0
## 163    884   H_70_74    13
## 164    888   H_70_74     1
## 165    888   H_70_74     2
## 166    001   H_75_79    91
## 167    001   H_75_79     7
## 168    001   H_75_79    22
## 169    343   H_75_79     3
## 170    343   H_75_79     7
## 171    883   H_75_79     0
## 172    883   H_75_79     5
## 173    884   H_75_79     0
## 174    884   H_75_79     2
## 175    888   H_75_79     1
## 176    888   H_75_79     3
## 177    001   H_80_84    32
## 178    001   H_80_84     2
## 179    001   H_80_84    12
## 180    343   H_80_84     2
## 181    343   H_80_84     5
## 182    883   H_80_84     1
## 183    883   H_80_84     2
## 184    884   H_80_84     0
## 185    884   H_80_84     4
## 186    888   H_80_84     0
## 187    888   H_80_84     1
## 188    001   H_85_89    21
## 189    001   H_85_89     2
## 190    001   H_85_89     5
## 191    343   H_85_89     0
## 192    343   H_85_89     3
## 193    883   H_85_89     0
## 194    883   H_85_89     1
## 195    884   H_85_89     0
## 196    884   H_85_89     2
## 197    888   H_85_89     0
## 198    888   H_85_89     1
## 199    001   H_90_94     3
## 200    001   H_90_94     1
## 201    001   H_90_94     1
## 202    343   H_90_94     0
## 203    343   H_90_94     2
## 204    883   H_90_94     0
## 205    883   H_90_94     1
## 206    884   H_90_94     0
## 207    884   H_90_94     0
## 208    888   H_90_94     0
## 209    888   H_90_94     0
## 210    001   H_95_99     3
## 211    001   H_95_99     1
## 212    001   H_95_99     0
## 213    343   H_95_99     1
## 214    343   H_95_99     0
## 215    883   H_95_99     0
## 216    883   H_95_99     0
## 217    884   H_95_99     0
## 218    884   H_95_99     1
## 219    888   H_95_99     0
## 220    888   H_95_99     0
## 221    001 H_100_104     2
## 222    001 H_100_104     0
## 223    001 H_100_104     1
## 224    343 H_100_104     0
## 225    343 H_100_104     1
## 226    883 H_100_104     0
## 227    883 H_100_104     0
## 228    884 H_100_104     0
## 229    884 H_100_104     0
## 230    888 H_100_104     0
## 231    888 H_100_104     0
## 232    001   M_00_04   913
## 233    001   M_00_04   134
## 234    001   M_00_04   321
## 235    343   M_00_04    52
## 236    343   M_00_04   320
## 237    883   M_00_04     6
## 238    883   M_00_04    66
## 239    884   M_00_04     0
## 240    884   M_00_04    61
## 241    888   M_00_04    11
## 242    888   M_00_04    35
## 243    001   M_05_09   962
## 244    001   M_05_09   137
## 245    001   M_05_09   869
## 246    343   M_05_09    58
## 247    343   M_05_09   722
## 248    883   M_05_09    17
## 249    883   M_05_09    99
## 250    884   M_05_09     0
## 251    884   M_05_09   175
## 252    888   M_05_09    12
## 253    888   M_05_09    57
## 254    001   M_10_14   973
## 255    001   M_10_14   128
## 256    001   M_10_14   705
## 257    343   M_10_14    42
## 258    343   M_10_14   634
## 259    883   M_10_14    28
## 260    883   M_10_14    90
## 261    884   M_10_14     0
## 262    884   M_10_14   134
## 263    888   M_10_14     6
## 264    888   M_10_14    69
## 265    001   M_15_19  1002
## 266    001   M_15_19   152
## 267    001   M_15_19   555
## 268    343   M_15_19    53
## 269    343   M_15_19   386
## 270    883   M_15_19    21
## 271    883   M_15_19    66
## 272    884   M_15_19     1
## 273    884   M_15_19    79
## 274    888   M_15_19     5
## 275    888   M_15_19    40
## 276    001   M_20_24   978
## 277    001   M_20_24   104
## 278    001   M_20_24   263
## 279    343   M_20_24    54
## 280    343   M_20_24   212
## 281    883   M_20_24     4
## 282    883   M_20_24    41
## 283    884   M_20_24     2
## 284    884   M_20_24    53
## 285    888   M_20_24     3
## 286    888   M_20_24    30
## 287    001   M_25_29   852
## 288    001   M_25_29   100
## 289    001   M_25_29   223
## 290    343   M_25_29    39
## 291    343   M_25_29   143
## 292    883   M_25_29    10
## 293    883   M_25_29    37
## 294    884   M_25_29     2
## 295    884   M_25_29    45
## 296    888   M_25_29     8
## 297    888   M_25_29    17
## 298    001   M_30_34   725
## 299    001   M_30_34    64
## 300    001   M_30_34   184
## 301    343   M_30_34    26
## 302    343   M_30_34   110
## 303    883   M_30_34     3
## 304    883   M_30_34    37
## 305    884   M_30_34     0
## 306    884   M_30_34    36
## 307    888   M_30_34     4
## 308    888   M_30_34    15
## 309    001   M_35_39   711
## 310    001   M_35_39    70
## 311    001   M_35_39   143
## 312    343   M_35_39    22
## 313    343   M_35_39    90
## 314    883   M_35_39     7
## 315    883   M_35_39    20
## 316    884   M_35_39     0
## 317    884   M_35_39    39
## 318    888   M_35_39     5
## 319    888   M_35_39    17
## 320    001   M_40_44   593
## 321    001   M_40_44    40
## 322    001   M_40_44   140
## 323    343   M_40_44    24
## 324    343   M_40_44    81
## 325    883   M_40_44     5
## 326    883   M_40_44    25
## 327    884   M_40_44     1
## 328    884   M_40_44    30
## 329    888   M_40_44     3
## 330    888   M_40_44    14
## 331    001   M_45_49   495
## 332    001   M_45_49    45
## 333    001   M_45_49    87
## 334    343   M_45_49    13
## 335    343   M_45_49    68
## 336    883   M_45_49     2
## 337    883   M_45_49    23
## 338    884   M_45_49     0
## 339    884   M_45_49    36
## 340    888   M_45_49     2
## 341    888   M_45_49     1
## 342    001   M_50_54   425
## 343    001   M_50_54    38
## 344    001   M_50_54   100
## 345    343   M_50_54    17
## 346    343   M_50_54    46
## 347    883   M_50_54     2
## 348    883   M_50_54    22
## 349    884   M_50_54     0
## 350    884   M_50_54    18
## 351    888   M_50_54     1
## 352    888   M_50_54     9
## 353    001   M_55_59   326
## 354    001   M_55_59    25
## 355    001   M_55_59    96
## 356    343   M_55_59    15
## 357    343   M_55_59    42
## 358    883   M_55_59     3
## 359    883   M_55_59    10
## 360    884   M_55_59     0
## 361    884   M_55_59    14
## 362    888   M_55_59     4
## 363    888   M_55_59     4
## 364    001   M_60_64   200
## 365    001   M_60_64    20
## 366    001   M_60_64    40
## 367    343   M_60_64     2
## 368    343   M_60_64    15
## 369    883   M_60_64     1
## 370    883   M_60_64    12
## 371    884   M_60_64     0
## 372    884   M_60_64    11
## 373    888   M_60_64     1
## 374    888   M_60_64     2
## 375    001   M_65_69   153
## 376    001   M_65_69    12
## 377    001   M_65_69    42
## 378    343   M_65_69     4
## 379    343   M_65_69    19
## 380    883   M_65_69     0
## 381    883   M_65_69     6
## 382    884   M_65_69     0
## 383    884   M_65_69    16
## 384    888   M_65_69     4
## 385    888   M_65_69     3
## 386    001   M_70_74   105
## 387    001   M_70_74    11
## 388    001   M_70_74    33
## 389    343   M_70_74     1
## 390    343   M_70_74    16
## 391    883   M_70_74     0
## 392    883   M_70_74     5
## 393    884   M_70_74     0
## 394    884   M_70_74    14
## 395    888   M_70_74     1
## 396    888   M_70_74     4
## 397    001   M_75_79    81
## 398    001   M_75_79     9
## 399    001   M_75_79    22
## 400    343   M_75_79     4
## 401    343   M_75_79     7
## 402    883   M_75_79     0
## 403    883   M_75_79     3
## 404    884   M_75_79     0
## 405    884   M_75_79     8
## 406    888   M_75_79     0
## 407    888   M_75_79     0
## 408    001   M_80_84    30
## 409    001   M_80_84     4
## 410    001   M_80_84    12
## 411    343   M_80_84     0
## 412    343   M_80_84     4
## 413    883   M_80_84     2
## 414    883   M_80_84     1
## 415    884   M_80_84     0
## 416    884   M_80_84     2
## 417    888   M_80_84     0
## 418    888   M_80_84     1
## 419    001   M_85_89    18
## 420    001   M_85_89     0
## 421    001   M_85_89     5
## 422    343   M_85_89     0
## 423    343   M_85_89     2
## 424    883   M_85_89     0
## 425    883   M_85_89     1
## 426    884   M_85_89     0
## 427    884   M_85_89     2
## 428    888   M_85_89     0
## 429    888   M_85_89     1
## 430    001   M_90_94     8
## 431    001   M_90_94     0
## 432    001   M_90_94     1
## 433    343   M_90_94     0
## 434    343   M_90_94     1
## 435    883   M_90_94     0
## 436    883   M_90_94     1
## 437    884   M_90_94     0
## 438    884   M_90_94     0
## 439    888   M_90_94     0
## 440    888   M_90_94     0
## 441    001   M_95_99     1
## 442    001   M_95_99     2
## 443    001   M_95_99     3
## 444    343   M_95_99     0
## 445    343   M_95_99     0
## 446    883   M_95_99     0
## 447    883   M_95_99     0
## 448    884   M_95_99     0
## 449    884   M_95_99     0
## 450    888   M_95_99     0
## 451    888   M_95_99     1
## 452    001 M_100_104     0
## 453    001 M_100_104     1
## 454    001 M_100_104     1
## 455    343 M_100_104     0
## 456    343 M_100_104     0
## 457    883 M_100_104     0
## 458    883 M_100_104     0
## 459    884 M_100_104     0
## 460    884 M_100_104     2
## 461    888 M_100_104     0
## 462    888 M_100_104     0
# Crear columna 'Sexo' a partir de los primeros caracteres de la columna 'variable'
poblacion_comb$Sexo <- as.factor(substr(poblacion_comb$variable, start = 1, stop = 1))

# Crear columna 'Gquinquenal' a partir de los caracteres 3 a 8 de la columna 'variable'
poblacion_comb$Gquinquenal <- substr(poblacion_comb$variable, start = 3, stop = 9)

# Verificar si la columna 'Gquinquenal' existe antes de convertirla en factor
if("Gquinquenal" %in% colnames(poblacion_comb)) {
  poblacion_comb$Gquinquenal <- factor(poblacion_comb$Gquinquenal, 
                                       levels = c("00_04", "05_09", "10_14", "15_19", "20_24", 
                                                  "25_29", "30_34", "35_39", "40_44", "45_49", 
                                                  "50_54", "55_59", "60_64", "65_69", "70_74", 
                                                  "75_79", "80_84", "85_89", "90_94", "95_99", 
                                                  "100_104"), 
                                       ordered = TRUE)
} else {
  stop("La columna 'Gquinquenal' no existe en el dataframe.")
}

# Asegúrate de que la columna 'value' sea numérica
poblacion_comb$value <- as.numeric(as.character(poblacion_comb$value))

# Agrupar y sumar
pop_comb <- poblacion_comb %>%
  group_by(Gquinquenal, Sexo) %>%
  summarise(value = sum(value, na.rm = TRUE)) %>%  # Sumar los valores numéricos
  select(Gquinquenal, Sexo, value)
## `summarise()` has grouped output by 'Gquinquenal'. You can override using the
## `.groups` argument.
# Verifica el resultado
print(pop_comb)
## # A tibble: 42 × 3
## # Groups:   Gquinquenal [21]
##    Gquinquenal Sexo  value
##    <ord>       <fct> <dbl>
##  1 00_04       H      2004
##  2 00_04       M      1919
##  3 05_09       H      3155
##  4 05_09       M      3108
##  5 10_14       H      3060
##  6 10_14       M      2809
##  7 15_19       H      2780
##  8 15_19       M      2360
##  9 20_24       H      2209
## 10 20_24       M      1744
## # ℹ 32 more rows
poblacion_comb <- poblacion_comb[, c(3:5)]  # Seleccionar solo las columnas 3 a 5
poblacion_comb <- poblacion_comb[, c(3, 2, 1)]  # Reorganizar el orden de las columnas
print(poblacion_comb)
##     Gquinquenal Sexo value
## 1         00_04    H   949
## 2         00_04    H   140
## 3         00_04    H   343
## 4         00_04    H    54
## 5         00_04    H   357
## 6         00_04    H     5
## 7         00_04    H    48
## 8         00_04    H     0
## 9         00_04    H    68
## 10        00_04    H     7
## 11        00_04    H    33
## 12        05_09    H   994
## 13        05_09    H   162
## 14        05_09    H   879
## 15        05_09    H    65
## 16        05_09    H   708
## 17        05_09    H    17
## 18        05_09    H   111
## 19        05_09    H     0
## 20        05_09    H   152
## 21        05_09    H     9
## 22        05_09    H    58
## 23        10_14    H   995
## 24        10_14    H   136
## 25        10_14    H   895
## 26        10_14    H    48
## 27        10_14    H   662
## 28        10_14    H    36
## 29        10_14    H    93
## 30        10_14    H     0
## 31        10_14    H   129
## 32        10_14    H    13
## 33        10_14    H    53
## 34        15_19    H  1062
## 35        15_19    H   116
## 36        15_19    H   685
## 37        15_19    H    55
## 38        15_19    H   555
## 39        15_19    H    33
## 40        15_19    H    59
## 41        15_19    H     0
## 42        15_19    H   148
## 43        15_19    H     8
## 44        15_19    H    59
## 45        20_24    H  1091
## 46        20_24    H   109
## 47        20_24    H   451
## 48        20_24    H    60
## 49        20_24    H   343
## 50        20_24    H    12
## 51        20_24    H    49
## 52        20_24    H     2
## 53        20_24    H    54
## 54        20_24    H     7
## 55        20_24    H    31
## 56        25_29    H   818
## 57        25_29    H    79
## 58        25_29    H   250
## 59        25_29    H    40
## 60        25_29    H   166
## 61        25_29    H     8
## 62        25_29    H    36
## 63        25_29    H     0
## 64        25_29    H    40
## 65        25_29    H     7
## 66        25_29    H    16
## 67        30_34    H   726
## 68        30_34    H    72
## 69        30_34    H   226
## 70        30_34    H    28
## 71        30_34    H   114
## 72        30_34    H     4
## 73        30_34    H    30
## 74        30_34    H     1
## 75        30_34    H    44
## 76        30_34    H     4
## 77        30_34    H    22
## 78        35_39    H   637
## 79        35_39    H    91
## 80        35_39    H   232
## 81        35_39    H    19
## 82        35_39    H   102
## 83        35_39    H     3
## 84        35_39    H    38
## 85        35_39    H     1
## 86        35_39    H    37
## 87        35_39    H     8
## 88        35_39    H    13
## 89        40_44    H   528
## 90        40_44    H    56
## 91        40_44    H   162
## 92        40_44    H    25
## 93        40_44    H    79
## 94        40_44    H     2
## 95        40_44    H    37
## 96        40_44    H     0
## 97        40_44    H    43
## 98        40_44    H     6
## 99        40_44    H    13
## 100       45_49    H   520
## 101       45_49    H    55
## 102       45_49    H   112
## 103       45_49    H    17
## 104       45_49    H    90
## 105       45_49    H     4
## 106       45_49    H    27
## 107       45_49    H     1
## 108       45_49    H    35
## 109       45_49    H     3
## 110       45_49    H     6
## 111       50_54    H   415
## 112       50_54    H    43
## 113       50_54    H   113
## 114       50_54    H    19
## 115       50_54    H    67
## 116       50_54    H     3
## 117       50_54    H    20
## 118       50_54    H     0
## 119       50_54    H    33
## 120       50_54    H     3
## 121       50_54    H    13
## 122       55_59    H   368
## 123       55_59    H    44
## 124       55_59    H   117
## 125       55_59    H    22
## 126       55_59    H    55
## 127       55_59    H     6
## 128       55_59    H    11
## 129       55_59    H     0
## 130       55_59    H    22
## 131       55_59    H     1
## 132       55_59    H    11
## 133       60_64    H   225
## 134       60_64    H    30
## 135       60_64    H    71
## 136       60_64    H    12
## 137       60_64    H    17
## 138       60_64    H     1
## 139       60_64    H    15
## 140       60_64    H     0
## 141       60_64    H    17
## 142       60_64    H     1
## 143       60_64    H     3
## 144       65_69    H   155
## 145       65_69    H    15
## 146       65_69    H    51
## 147       65_69    H     9
## 148       65_69    H    25
## 149       65_69    H     1
## 150       65_69    H     9
## 151       65_69    H     0
## 152       65_69    H    13
## 153       65_69    H     3
## 154       65_69    H     2
## 155       70_74    H   140
## 156       70_74    H    14
## 157       70_74    H    34
## 158       70_74    H     7
## 159       70_74    H    19
## 160       70_74    H     2
## 161       70_74    H     5
## 162       70_74    H     0
## 163       70_74    H    13
## 164       70_74    H     1
## 165       70_74    H     2
## 166       75_79    H    91
## 167       75_79    H     7
## 168       75_79    H    22
## 169       75_79    H     3
## 170       75_79    H     7
## 171       75_79    H     0
## 172       75_79    H     5
## 173       75_79    H     0
## 174       75_79    H     2
## 175       75_79    H     1
## 176       75_79    H     3
## 177       80_84    H    32
## 178       80_84    H     2
## 179       80_84    H    12
## 180       80_84    H     2
## 181       80_84    H     5
## 182       80_84    H     1
## 183       80_84    H     2
## 184       80_84    H     0
## 185       80_84    H     4
## 186       80_84    H     0
## 187       80_84    H     1
## 188       85_89    H    21
## 189       85_89    H     2
## 190       85_89    H     5
## 191       85_89    H     0
## 192       85_89    H     3
## 193       85_89    H     0
## 194       85_89    H     1
## 195       85_89    H     0
## 196       85_89    H     2
## 197       85_89    H     0
## 198       85_89    H     1
## 199       90_94    H     3
## 200       90_94    H     1
## 201       90_94    H     1
## 202       90_94    H     0
## 203       90_94    H     2
## 204       90_94    H     0
## 205       90_94    H     1
## 206       90_94    H     0
## 207       90_94    H     0
## 208       90_94    H     0
## 209       90_94    H     0
## 210       95_99    H     3
## 211       95_99    H     1
## 212       95_99    H     0
## 213       95_99    H     1
## 214       95_99    H     0
## 215       95_99    H     0
## 216       95_99    H     0
## 217       95_99    H     0
## 218       95_99    H     1
## 219       95_99    H     0
## 220       95_99    H     0
## 221     100_104    H     2
## 222     100_104    H     0
## 223     100_104    H     1
## 224     100_104    H     0
## 225     100_104    H     1
## 226     100_104    H     0
## 227     100_104    H     0
## 228     100_104    H     0
## 229     100_104    H     0
## 230     100_104    H     0
## 231     100_104    H     0
## 232       00_04    M   913
## 233       00_04    M   134
## 234       00_04    M   321
## 235       00_04    M    52
## 236       00_04    M   320
## 237       00_04    M     6
## 238       00_04    M    66
## 239       00_04    M     0
## 240       00_04    M    61
## 241       00_04    M    11
## 242       00_04    M    35
## 243       05_09    M   962
## 244       05_09    M   137
## 245       05_09    M   869
## 246       05_09    M    58
## 247       05_09    M   722
## 248       05_09    M    17
## 249       05_09    M    99
## 250       05_09    M     0
## 251       05_09    M   175
## 252       05_09    M    12
## 253       05_09    M    57
## 254       10_14    M   973
## 255       10_14    M   128
## 256       10_14    M   705
## 257       10_14    M    42
## 258       10_14    M   634
## 259       10_14    M    28
## 260       10_14    M    90
## 261       10_14    M     0
## 262       10_14    M   134
## 263       10_14    M     6
## 264       10_14    M    69
## 265       15_19    M  1002
## 266       15_19    M   152
## 267       15_19    M   555
## 268       15_19    M    53
## 269       15_19    M   386
## 270       15_19    M    21
## 271       15_19    M    66
## 272       15_19    M     1
## 273       15_19    M    79
## 274       15_19    M     5
## 275       15_19    M    40
## 276       20_24    M   978
## 277       20_24    M   104
## 278       20_24    M   263
## 279       20_24    M    54
## 280       20_24    M   212
## 281       20_24    M     4
## 282       20_24    M    41
## 283       20_24    M     2
## 284       20_24    M    53
## 285       20_24    M     3
## 286       20_24    M    30
## 287       25_29    M   852
## 288       25_29    M   100
## 289       25_29    M   223
## 290       25_29    M    39
## 291       25_29    M   143
## 292       25_29    M    10
## 293       25_29    M    37
## 294       25_29    M     2
## 295       25_29    M    45
## 296       25_29    M     8
## 297       25_29    M    17
## 298       30_34    M   725
## 299       30_34    M    64
## 300       30_34    M   184
## 301       30_34    M    26
## 302       30_34    M   110
## 303       30_34    M     3
## 304       30_34    M    37
## 305       30_34    M     0
## 306       30_34    M    36
## 307       30_34    M     4
## 308       30_34    M    15
## 309       35_39    M   711
## 310       35_39    M    70
## 311       35_39    M   143
## 312       35_39    M    22
## 313       35_39    M    90
## 314       35_39    M     7
## 315       35_39    M    20
## 316       35_39    M     0
## 317       35_39    M    39
## 318       35_39    M     5
## 319       35_39    M    17
## 320       40_44    M   593
## 321       40_44    M    40
## 322       40_44    M   140
## 323       40_44    M    24
## 324       40_44    M    81
## 325       40_44    M     5
## 326       40_44    M    25
## 327       40_44    M     1
## 328       40_44    M    30
## 329       40_44    M     3
## 330       40_44    M    14
## 331       45_49    M   495
## 332       45_49    M    45
## 333       45_49    M    87
## 334       45_49    M    13
## 335       45_49    M    68
## 336       45_49    M     2
## 337       45_49    M    23
## 338       45_49    M     0
## 339       45_49    M    36
## 340       45_49    M     2
## 341       45_49    M     1
## 342       50_54    M   425
## 343       50_54    M    38
## 344       50_54    M   100
## 345       50_54    M    17
## 346       50_54    M    46
## 347       50_54    M     2
## 348       50_54    M    22
## 349       50_54    M     0
## 350       50_54    M    18
## 351       50_54    M     1
## 352       50_54    M     9
## 353       55_59    M   326
## 354       55_59    M    25
## 355       55_59    M    96
## 356       55_59    M    15
## 357       55_59    M    42
## 358       55_59    M     3
## 359       55_59    M    10
## 360       55_59    M     0
## 361       55_59    M    14
## 362       55_59    M     4
## 363       55_59    M     4
## 364       60_64    M   200
## 365       60_64    M    20
## 366       60_64    M    40
## 367       60_64    M     2
## 368       60_64    M    15
## 369       60_64    M     1
## 370       60_64    M    12
## 371       60_64    M     0
## 372       60_64    M    11
## 373       60_64    M     1
## 374       60_64    M     2
## 375       65_69    M   153
## 376       65_69    M    12
## 377       65_69    M    42
## 378       65_69    M     4
## 379       65_69    M    19
## 380       65_69    M     0
## 381       65_69    M     6
## 382       65_69    M     0
## 383       65_69    M    16
## 384       65_69    M     4
## 385       65_69    M     3
## 386       70_74    M   105
## 387       70_74    M    11
## 388       70_74    M    33
## 389       70_74    M     1
## 390       70_74    M    16
## 391       70_74    M     0
## 392       70_74    M     5
## 393       70_74    M     0
## 394       70_74    M    14
## 395       70_74    M     1
## 396       70_74    M     4
## 397       75_79    M    81
## 398       75_79    M     9
## 399       75_79    M    22
## 400       75_79    M     4
## 401       75_79    M     7
## 402       75_79    M     0
## 403       75_79    M     3
## 404       75_79    M     0
## 405       75_79    M     8
## 406       75_79    M     0
## 407       75_79    M     0
## 408       80_84    M    30
## 409       80_84    M     4
## 410       80_84    M    12
## 411       80_84    M     0
## 412       80_84    M     4
## 413       80_84    M     2
## 414       80_84    M     1
## 415       80_84    M     0
## 416       80_84    M     2
## 417       80_84    M     0
## 418       80_84    M     1
## 419       85_89    M    18
## 420       85_89    M     0
## 421       85_89    M     5
## 422       85_89    M     0
## 423       85_89    M     2
## 424       85_89    M     0
## 425       85_89    M     1
## 426       85_89    M     0
## 427       85_89    M     2
## 428       85_89    M     0
## 429       85_89    M     1
## 430       90_94    M     8
## 431       90_94    M     0
## 432       90_94    M     1
## 433       90_94    M     0
## 434       90_94    M     1
## 435       90_94    M     0
## 436       90_94    M     1
## 437       90_94    M     0
## 438       90_94    M     0
## 439       90_94    M     0
## 440       90_94    M     0
## 441       95_99    M     1
## 442       95_99    M     2
## 443       95_99    M     3
## 444       95_99    M     0
## 445       95_99    M     0
## 446       95_99    M     0
## 447       95_99    M     0
## 448       95_99    M     0
## 449       95_99    M     0
## 450       95_99    M     0
## 451       95_99    M     1
## 452     100_104    M     0
## 453     100_104    M     1
## 454     100_104    M     1
## 455     100_104    M     0
## 456     100_104    M     0
## 457     100_104    M     0
## 458     100_104    M     0
## 459     100_104    M     0
## 460     100_104    M     2
## 461     100_104    M     0
## 462     100_104    M     0
# Reestructuración para tener 'Hombres' y 'Mujeres' en columnas separadas
poblacion_comb <- reshape(data = poblacion_comb,
                          idvar = "Gquinquenal",
                          v.names = c("value"),
                          timevar = "Sexo",
                          direction = "wide")
## Warning in reshapeWide(data, idvar = idvar, timevar = timevar, varying =
## varying, : multiple rows match for Sexo=H: first taken
## Warning in reshapeWide(data, idvar = idvar, timevar = timevar, varying =
## varying, : multiple rows match for Sexo=M: first taken
# Verificar el nombre de las columnas
print(colnames(poblacion_comb))
## [1] "Gquinquenal" "value.H"     "value.M"
# Renombrar columnas
poblacion_comb <- poblacion_comb %>%
  rename(Hombres = value.H, Mujeres = value.M)

# Calcular la población total
poblacion_comb$Poblacion <- poblacion_comb$Hombres + poblacion_comb$Mujeres
print(poblacion_comb)
##     Gquinquenal Hombres Mujeres Poblacion
## 1         00_04     949     913      1862
## 12        05_09     994     962      1956
## 23        10_14     995     973      1968
## 34        15_19    1062    1002      2064
## 45        20_24    1091     978      2069
## 56        25_29     818     852      1670
## 67        30_34     726     725      1451
## 78        35_39     637     711      1348
## 89        40_44     528     593      1121
## 100       45_49     520     495      1015
## 111       50_54     415     425       840
## 122       55_59     368     326       694
## 133       60_64     225     200       425
## 144       65_69     155     153       308
## 155       70_74     140     105       245
## 166       75_79      91      81       172
## 177       80_84      32      30        62
## 188       85_89      21      18        39
## 199       90_94       3       8        11
## 210       95_99       3       1         4
## 221     100_104       2       0         2
# Calcular la población total para obtener proporciones sin multiplicar por 100
pop_comb <- poblacion_comb %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH),   # Sin multiplicar por 100
         Mujeres = (Mujeres / totM)) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Gráfico de pirámide poblacional combinando clases en proporciones
ggplot(pop_comb, aes(x = Gquinquenal, y = `Poblacion por Sexo`, fill = Sexo)) +
  
  # Sección de HOMBRES (en proporciones negativas)
  geom_bar(data = subset(pop_comb, Sexo == "Hombres") %>% 
             mutate(`Poblacion por Sexo` = -`Poblacion por Sexo`),
           stat = "identity", width = 0.5, fill = "blue") +
  
  # Sección de MUJERES
  geom_bar(data = subset(pop_comb, Sexo == "Mujeres"),
           stat = "identity", width = 0.5, fill = "pink") +
  
  # Cambio de coordenadas para hacer horizontal
  coord_flip() +
  
  # Tema y estilos gráficos
  ggthemes::theme_tufte() +
  theme(plot.title = element_text(hjust = 0.5, size = 20),
        axis.text.x = element_text(),
        axis.text.y = element_text()) +
  
  # Etiquetas del gráfico
  labs(title = "Pirámide Poblacional General, 2018",
       x = "",
       y = "Hombres                        Mujeres",
       caption = "Fuente: DANE. \nCNPV 2018. Tabulados de Población") +
  
  # Escala de proporciones en el eje Y, ajustada en intervalos de 0.02
  scale_y_continuous(breaks = seq(-0.12, 0.12, by = 0.02),  # Proporciones en vez de porcentajes
                     labels = paste0(c(seq(0.12, 0, by = -0.02), seq(0.02, 0.12, by = 0.02))))

La pirámide poblacional muestra una distribución por sexo y edad, con una base amplia que indica una población mayoritariamente joven, especialmente en los grupos de 0 a 29 años. El grupo más numeroso es el de 20 a 24 años, lo que refleja una alta natalidad reciente. Notamos un incremento de la población femenina frente a los hombres desde la edad de 25 a 29 años, sin embargo, en edades más avanzadas se mantiene un comportamiendo de una población donde ambos sexos tienen una presencia relativamente uniforme, hasta la vejez.

Pirámide porcentual Cabecera Urbana
# Seleccionar columnas de la 2 a la 45
poblacioncm <- tabla_PersonaHogar[, 2:45]  
print(poblacioncm)  # Verifica el dataframe
##    U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1     001        1     949     994     995    1062    1091     818     726
## 2     001        2     140     162     136     116     109      79      72
## 3     001        3     343     879     895     685     451     250     226
## 4     343        2      54      65      48      55      60      40      28
## 5     343        3     357     708     662     555     343     166     114
## 6     883        2       5      17      36      33      12       8       4
## 7     883        3      48     111      93      59      49      36      30
## 8     884        2       0       0       0       0       2       0       1
## 9     884        3      68     152     129     148      54      40      44
## 10    888        2       7       9      13       8       7       7       4
## 11    888        3      33      58      53      59      31      16      22
##    H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1      637     528     520     415     368     225     155     140      91
## 2       91      56      55      43      44      30      15      14       7
## 3      232     162     112     113     117      71      51      34      22
## 4       19      25      17      19      22      12       9       7       3
## 5      102      79      90      67      55      17      25      19       7
## 6        3       2       4       3       6       1       1       2       0
## 7       38      37      27      20      11      15       9       5       5
## 8        1       0       1       0       0       0       0       0       0
## 9       37      43      35      33      22      17      13      13       2
## 10       8       6       3       3       1       1       3       1       1
## 11      13      13       6      13      11       3       2       2       3
##    H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1       32      21       3       3         2     913     962     973    1002
## 2        2       2       1       1         0     134     137     128     152
## 3       12       5       1       0         1     321     869     705     555
## 4        2       0       0       1         0      52      58      42      53
## 5        5       3       2       0         1     320     722     634     386
## 6        1       0       0       0         0       6      17      28      21
## 7        2       1       1       0         0      66      99      90      66
## 8        0       0       0       0         0       0       0       0       1
## 9        4       2       0       1         0      61     175     134      79
## 10       0       0       0       0         0      11      12       6       5
## 11       1       1       0       0         0      35      57      69      40
##    M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1      978     852     725     711     593     495     425     326     200
## 2      104     100      64      70      40      45      38      25      20
## 3      263     223     184     143     140      87     100      96      40
## 4       54      39      26      22      24      13      17      15       2
## 5      212     143     110      90      81      68      46      42      15
## 6        4      10       3       7       5       2       2       3       1
## 7       41      37      37      20      25      23      22      10      12
## 8        2       2       0       0       1       0       0       0       0
## 9       53      45      36      39      30      36      18      14      11
## 10       3       8       4       5       3       2       1       4       1
## 11      30      17      15      17      14       1       9       4       2
##    M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      153     105      81      30      18       8       1         0
## 2       12      11       9       4       0       0       2         1
## 3       42      33      22      12       5       1       3         1
## 4        4       1       4       0       0       0       0         0
## 5       19      16       7       4       2       1       0         0
## 6        0       0       0       2       0       0       0         0
## 7        6       5       3       1       1       1       0         0
## 8        0       0       0       0       0       0       0         0
## 9       16      14       8       2       2       0       0         2
## 10       4       1       0       0       0       0       0         0
## 11       3       4       0       1       1       0       1         0
# Filtrar solo donde UA_CLASE == 1 (Centros Municipales)
poblacioncm <- poblacioncm %>%
  filter(UA_CLASE == 1)  
print(poblacioncm)  # Verifica los datos después de filtrar
##   U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1    001        1     949     994     995    1062    1091     818     726
##   H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1     637     528     520     415     368     225     155     140      91
##   H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1      32      21       3       3         2     913     962     973    1002
##   M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1     978     852     725     711     593     495     425     326     200
##   M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1     153     105      81      30      18       8       1         0
# Eliminar la segunda columna
poblacioncm <- poblacioncm[,-c(2)]  
print(poblacioncm)  # Verifica el dataframe sin la columna
##   U_MPIO H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34 H_35_39
## 1    001     949     994     995    1062    1091     818     726     637
##   H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79 H_80_84
## 1     528     520     415     368     225     155     140      91      32
##   H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19 M_20_24
## 1      21       3       3         2     913     962     973    1002     978
##   M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64 M_65_69
## 1     852     725     711     593     495     425     326     200     153
##   M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1     105      81      30      18       8       1         0
# Convertir el dataframe a formato largo
poblacioncm <- melt(poblacioncm, id.vars = "U_MPIO")  
print(poblacioncm)
##    U_MPIO  variable value
## 1     001   H_00_04   949
## 2     001   H_05_09   994
## 3     001   H_10_14   995
## 4     001   H_15_19  1062
## 5     001   H_20_24  1091
## 6     001   H_25_29   818
## 7     001   H_30_34   726
## 8     001   H_35_39   637
## 9     001   H_40_44   528
## 10    001   H_45_49   520
## 11    001   H_50_54   415
## 12    001   H_55_59   368
## 13    001   H_60_64   225
## 14    001   H_65_69   155
## 15    001   H_70_74   140
## 16    001   H_75_79    91
## 17    001   H_80_84    32
## 18    001   H_85_89    21
## 19    001   H_90_94     3
## 20    001   H_95_99     3
## 21    001 H_100_104     2
## 22    001   M_00_04   913
## 23    001   M_05_09   962
## 24    001   M_10_14   973
## 25    001   M_15_19  1002
## 26    001   M_20_24   978
## 27    001   M_25_29   852
## 28    001   M_30_34   725
## 29    001   M_35_39   711
## 30    001   M_40_44   593
## 31    001   M_45_49   495
## 32    001   M_50_54   425
## 33    001   M_55_59   326
## 34    001   M_60_64   200
## 35    001   M_65_69   153
## 36    001   M_70_74   105
## 37    001   M_75_79    81
## 38    001   M_80_84    30
## 39    001   M_85_89    18
## 40    001   M_90_94     8
## 41    001   M_95_99     1
## 42    001 M_100_104     0
# Crear columna 'Sexo' a partir de los primeros caracteres de la columna 'variable'
poblacioncm$Sexo <- as.factor(substr(poblacioncm$variable, start = 1, stop = 1))

# Crear columna 'Gquinquenal' a partir de los caracteres 3 a 8 de la columna 'variable'
poblacioncm$Gquinquenal <- substr(poblacioncm$variable, start = 3, stop = 9)

# Verificar si la columna 'Gquinquenal' existe antes de convertirla en factor
if("Gquinquenal" %in% colnames(poblacioncm)) {
  poblacioncm$Gquinquenal <- factor(poblacioncm$Gquinquenal, 
                                    levels = c("00_04", "05_09", "10_14", "15_19", "20_24", 
                                               "25_29", "30_34", "35_39", "40_44", "45_49", 
                                               "50_54", "55_59", "60_64", "65_69", "70_74", 
                                               "75_79", "80_84", "85_89", "90_94", "95_99", 
                                               "100_104"), 
                                    ordered = TRUE)
} else {
  stop("La columna 'Gquinquenal' no existe en el dataframe.")
}

# Asegúrate de que la columna 'value' sea numérica
poblacioncm$value <- as.numeric(as.character(poblacioncm$value))

# Agrupar y sumar
pop_cm <- poblacioncm %>%
  group_by(Gquinquenal, Sexo) %>%
  summarise(value = sum(value, na.rm = TRUE)) %>%  # Sumar los valores numéricos
  select(Gquinquenal, Sexo, value)
## `summarise()` has grouped output by 'Gquinquenal'. You can override using the
## `.groups` argument.
# Verifica el resultado
print(pop_cm)
## # A tibble: 42 × 3
## # Groups:   Gquinquenal [21]
##    Gquinquenal Sexo  value
##    <ord>       <fct> <dbl>
##  1 00_04       H       949
##  2 00_04       M       913
##  3 05_09       H       994
##  4 05_09       M       962
##  5 10_14       H       995
##  6 10_14       M       973
##  7 15_19       H      1062
##  8 15_19       M      1002
##  9 20_24       H      1091
## 10 20_24       M       978
## # ℹ 32 more rows
poblacioncm <- poblacioncm[, c(3:5)]  # Seleccionar solo las columnas 3 a 5
poblacioncm <- poblacioncm[, c(3, 2, 1)]  # Reorganizar el orden de las columnas
print(poblacioncm)
##    Gquinquenal Sexo value
## 1        00_04    H   949
## 2        05_09    H   994
## 3        10_14    H   995
## 4        15_19    H  1062
## 5        20_24    H  1091
## 6        25_29    H   818
## 7        30_34    H   726
## 8        35_39    H   637
## 9        40_44    H   528
## 10       45_49    H   520
## 11       50_54    H   415
## 12       55_59    H   368
## 13       60_64    H   225
## 14       65_69    H   155
## 15       70_74    H   140
## 16       75_79    H    91
## 17       80_84    H    32
## 18       85_89    H    21
## 19       90_94    H     3
## 20       95_99    H     3
## 21     100_104    H     2
## 22       00_04    M   913
## 23       05_09    M   962
## 24       10_14    M   973
## 25       15_19    M  1002
## 26       20_24    M   978
## 27       25_29    M   852
## 28       30_34    M   725
## 29       35_39    M   711
## 30       40_44    M   593
## 31       45_49    M   495
## 32       50_54    M   425
## 33       55_59    M   326
## 34       60_64    M   200
## 35       65_69    M   153
## 36       70_74    M   105
## 37       75_79    M    81
## 38       80_84    M    30
## 39       85_89    M    18
## 40       90_94    M     8
## 41       95_99    M     1
## 42     100_104    M     0
# Reestructuración para tener 'Hombres' y 'Mujeres' en columnas separadas
poblacioncm <- reshape(data = poblacioncm,
                       idvar = "Gquinquenal",
                       v.names = c("value"),
                       timevar = "Sexo",
                       direction = "wide")

# Verificar el nombre de las columnas
print(colnames(poblacioncm))
## [1] "Gquinquenal" "value.H"     "value.M"
# Renombrar columnas
poblacioncm <- poblacioncm %>%
  rename(Hombres = value.H, Mujeres = value.M)

# Calcular la población total
poblacioncm$Poblacion <- poblacioncm$Hombres + poblacioncm$Mujeres
print(poblacioncm)
##    Gquinquenal Hombres Mujeres Poblacion
## 1        00_04     949     913      1862
## 2        05_09     994     962      1956
## 3        10_14     995     973      1968
## 4        15_19    1062    1002      2064
## 5        20_24    1091     978      2069
## 6        25_29     818     852      1670
## 7        30_34     726     725      1451
## 8        35_39     637     711      1348
## 9        40_44     528     593      1121
## 10       45_49     520     495      1015
## 11       50_54     415     425       840
## 12       55_59     368     326       694
## 13       60_64     225     200       425
## 14       65_69     155     153       308
## 15       70_74     140     105       245
## 16       75_79      91      81       172
## 17       80_84      32      30        62
## 18       85_89      21      18        39
## 19       90_94       3       8        11
## 20       95_99       3       1         4
## 21     100_104       2       0         2
# Procesar los datos para el gráfico
pop_cm <- poblacioncm %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH) * 100,
         Mujeres = (Mujeres / totM) * 100) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Calcular la población total para obtener proporciones sin multiplicar por 100
pop_cm <- poblacioncm %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH),   # Sin multiplicar por 100
         Mujeres = (Mujeres / totM)) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Gráfico de pirámide poblacional centros municipales en proporciones
ggplot(pop_cm, aes(x = Gquinquenal, y = `Poblacion por Sexo`, fill = Sexo)) +
  
  # Sección de HOMBRES (en proporciones negativas)
  geom_bar(data = subset(pop_cm, Sexo == "Hombres") %>% 
             mutate(`Poblacion por Sexo` = -`Poblacion por Sexo`),
           stat = "identity", width = 0.5, fill = "blue") +
  
  # Sección de MUJERES
  geom_bar(data = subset(pop_cm, Sexo == "Mujeres"),
           stat = "identity", width = 0.5, fill = "pink") +
  
  # Cambio de coordenadas para hacer horizontal
  coord_flip() +
  
  # Tema y estilos gráficos
  ggthemes::theme_tufte() +
  theme(plot.title = element_text(hjust = 0.5, size = 20),
        axis.text.x = element_text(),
        axis.text.y = element_text()) +
  
  # Etiquetas del gráfico
  labs(title = "Pirámide Poblacional Cabecera Urbana, 2018",
       x = "",
       y = "Hombres                        Mujeres",
       caption = "Fuente: DANE. \nCNPV 2018. Tabulados de Población") +
  
  # Escala de proporciones en el eje Y, ajustada en intervalos de 0.02
  scale_y_continuous(breaks = seq(-0.12, 0.12, by = 0.02),  # Proporciones en vez de porcentajes
                     labels = paste0(c(seq(0.12, 0, by = -0.02), seq(0.02, 0.12, by = 0.02))))

La pirámide poblacional del municipio del departamento de Guainía en 2018, podemos observar que la población se distribuye uniformemente en los primeros años de vida, sin embargo la presencia de los hombres es mayor desde el grupo etareo de 20 a 24 años. Después se vuelve a distribuir casi uniformemente la población, sin embargo en los grupos etareos más longevos se aprecia la presencia de la población masculina principalmente.

Pirámide porcentual Centro Poblacional

Este código realiza un análisis y visualización de la población en centros municipales, enfocándose en la creación de una pirámide poblacional que muestra la proporción de hombres y mujeres por grupos de edad (quinquenios). A continuación se resume cada paso:

Selección y filtrado de datos:

Se seleccionan las columnas relevantes del dataframe y se filtran los registros que corresponden a centros municipales (UA_CLASE == 1). Reestructuración de datos:

El dataframe se convierte a formato largo, donde cada fila representa un grupo de edad y sexo. Se crean nuevas columnas para identificar el sexo y el grupo de edad (quinquenios). Agrupación y suma:

Se agrupa la población por quinquenio y sexo, sumando el total de personas en cada categoría. Reestructuración para hombres y mujeres en columnas separadas:

El dataframe se reestructura nuevamente para tener las columnas “Hombres” y “Mujeres” separadas. Se calcula la población total y las proporciones de hombres y mujeres. Cálculo de proporciones:

Se calculan las proporciones de hombres y mujeres respecto al total de la población en cada grupo de edad, expresadas en forma de proporción (sin multiplicar por 100). Generación del gráfico de pirámide poblacional:

Utilizando ggplot, se crea una pirámide poblacional que muestra las proporciones de hombres y mujeres por grupo de edad, con los hombres representados en valores negativos para facilitar la comparación visual. Estilo y presentación del gráfico:

El gráfico se presenta con estilo personalizado, utilizando colores diferentes para hombres y mujeres, y mostrando una escala de proporciones ajustada.

## Pirámide porcentual Rural Centros Poblados

# Seleccionar columnas de la 2 a la 45
poblacioncp <- tabla_PersonaHogar[, 2:45]  
print(poblacioncp)  # Verifica el dataframe
##    U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1     001        1     949     994     995    1062    1091     818     726
## 2     001        2     140     162     136     116     109      79      72
## 3     001        3     343     879     895     685     451     250     226
## 4     343        2      54      65      48      55      60      40      28
## 5     343        3     357     708     662     555     343     166     114
## 6     883        2       5      17      36      33      12       8       4
## 7     883        3      48     111      93      59      49      36      30
## 8     884        2       0       0       0       0       2       0       1
## 9     884        3      68     152     129     148      54      40      44
## 10    888        2       7       9      13       8       7       7       4
## 11    888        3      33      58      53      59      31      16      22
##    H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1      637     528     520     415     368     225     155     140      91
## 2       91      56      55      43      44      30      15      14       7
## 3      232     162     112     113     117      71      51      34      22
## 4       19      25      17      19      22      12       9       7       3
## 5      102      79      90      67      55      17      25      19       7
## 6        3       2       4       3       6       1       1       2       0
## 7       38      37      27      20      11      15       9       5       5
## 8        1       0       1       0       0       0       0       0       0
## 9       37      43      35      33      22      17      13      13       2
## 10       8       6       3       3       1       1       3       1       1
## 11      13      13       6      13      11       3       2       2       3
##    H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1       32      21       3       3         2     913     962     973    1002
## 2        2       2       1       1         0     134     137     128     152
## 3       12       5       1       0         1     321     869     705     555
## 4        2       0       0       1         0      52      58      42      53
## 5        5       3       2       0         1     320     722     634     386
## 6        1       0       0       0         0       6      17      28      21
## 7        2       1       1       0         0      66      99      90      66
## 8        0       0       0       0         0       0       0       0       1
## 9        4       2       0       1         0      61     175     134      79
## 10       0       0       0       0         0      11      12       6       5
## 11       1       1       0       0         0      35      57      69      40
##    M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1      978     852     725     711     593     495     425     326     200
## 2      104     100      64      70      40      45      38      25      20
## 3      263     223     184     143     140      87     100      96      40
## 4       54      39      26      22      24      13      17      15       2
## 5      212     143     110      90      81      68      46      42      15
## 6        4      10       3       7       5       2       2       3       1
## 7       41      37      37      20      25      23      22      10      12
## 8        2       2       0       0       1       0       0       0       0
## 9       53      45      36      39      30      36      18      14      11
## 10       3       8       4       5       3       2       1       4       1
## 11      30      17      15      17      14       1       9       4       2
##    M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      153     105      81      30      18       8       1         0
## 2       12      11       9       4       0       0       2         1
## 3       42      33      22      12       5       1       3         1
## 4        4       1       4       0       0       0       0         0
## 5       19      16       7       4       2       1       0         0
## 6        0       0       0       2       0       0       0         0
## 7        6       5       3       1       1       1       0         0
## 8        0       0       0       0       0       0       0         0
## 9       16      14       8       2       2       0       0         2
## 10       4       1       0       0       0       0       0         0
## 11       3       4       0       1       1       0       1         0
# Filtrar solo donde UA_CLASE == 2 (Centros Poblados)
poblacioncp <- poblacioncp %>%
  filter(UA_CLASE == 2)  
print(poblacioncp)  # Verifica los datos después de filtrar
##   U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1    001        2     140     162     136     116     109      79      72
## 2    343        2      54      65      48      55      60      40      28
## 3    883        2       5      17      36      33      12       8       4
## 4    884        2       0       0       0       0       2       0       1
## 5    888        2       7       9      13       8       7       7       4
##   H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1      91      56      55      43      44      30      15      14       7
## 2      19      25      17      19      22      12       9       7       3
## 3       3       2       4       3       6       1       1       2       0
## 4       1       0       1       0       0       0       0       0       0
## 5       8       6       3       3       1       1       3       1       1
##   H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1       2       2       1       1         0     134     137     128     152
## 2       2       0       0       1         0      52      58      42      53
## 3       1       0       0       0         0       6      17      28      21
## 4       0       0       0       0         0       0       0       0       1
## 5       0       0       0       0         0      11      12       6       5
##   M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1     104     100      64      70      40      45      38      25      20
## 2      54      39      26      22      24      13      17      15       2
## 3       4      10       3       7       5       2       2       3       1
## 4       2       2       0       0       1       0       0       0       0
## 5       3       8       4       5       3       2       1       4       1
##   M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      12      11       9       4       0       0       2         1
## 2       4       1       4       0       0       0       0         0
## 3       0       0       0       2       0       0       0         0
## 4       0       0       0       0       0       0       0         0
## 5       4       1       0       0       0       0       0         0
# Eliminar la segunda columna
poblacioncp <- poblacioncp[,-c(2)]  
print(poblacioncp)  # Verifica el dataframe sin la columna
##   U_MPIO H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34 H_35_39
## 1    001     140     162     136     116     109      79      72      91
## 2    343      54      65      48      55      60      40      28      19
## 3    883       5      17      36      33      12       8       4       3
## 4    884       0       0       0       0       2       0       1       1
## 5    888       7       9      13       8       7       7       4       8
##   H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79 H_80_84
## 1      56      55      43      44      30      15      14       7       2
## 2      25      17      19      22      12       9       7       3       2
## 3       2       4       3       6       1       1       2       0       1
## 4       0       1       0       0       0       0       0       0       0
## 5       6       3       3       1       1       3       1       1       0
##   H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19 M_20_24
## 1       2       1       1         0     134     137     128     152     104
## 2       0       0       1         0      52      58      42      53      54
## 3       0       0       0         0       6      17      28      21       4
## 4       0       0       0         0       0       0       0       1       2
## 5       0       0       0         0      11      12       6       5       3
##   M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64 M_65_69
## 1     100      64      70      40      45      38      25      20      12
## 2      39      26      22      24      13      17      15       2       4
## 3      10       3       7       5       2       2       3       1       0
## 4       2       0       0       1       0       0       0       0       0
## 5       8       4       5       3       2       1       4       1       4
##   M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      11       9       4       0       0       2         1
## 2       1       4       0       0       0       0         0
## 3       0       0       2       0       0       0         0
## 4       0       0       0       0       0       0         0
## 5       1       0       0       0       0       0         0
# Convertir el dataframe a formato largo
poblacioncp <- melt(poblacioncp, id.vars = "U_MPIO")  
print(poblacioncp)
##     U_MPIO  variable value
## 1      001   H_00_04   140
## 2      343   H_00_04    54
## 3      883   H_00_04     5
## 4      884   H_00_04     0
## 5      888   H_00_04     7
## 6      001   H_05_09   162
## 7      343   H_05_09    65
## 8      883   H_05_09    17
## 9      884   H_05_09     0
## 10     888   H_05_09     9
## 11     001   H_10_14   136
## 12     343   H_10_14    48
## 13     883   H_10_14    36
## 14     884   H_10_14     0
## 15     888   H_10_14    13
## 16     001   H_15_19   116
## 17     343   H_15_19    55
## 18     883   H_15_19    33
## 19     884   H_15_19     0
## 20     888   H_15_19     8
## 21     001   H_20_24   109
## 22     343   H_20_24    60
## 23     883   H_20_24    12
## 24     884   H_20_24     2
## 25     888   H_20_24     7
## 26     001   H_25_29    79
## 27     343   H_25_29    40
## 28     883   H_25_29     8
## 29     884   H_25_29     0
## 30     888   H_25_29     7
## 31     001   H_30_34    72
## 32     343   H_30_34    28
## 33     883   H_30_34     4
## 34     884   H_30_34     1
## 35     888   H_30_34     4
## 36     001   H_35_39    91
## 37     343   H_35_39    19
## 38     883   H_35_39     3
## 39     884   H_35_39     1
## 40     888   H_35_39     8
## 41     001   H_40_44    56
## 42     343   H_40_44    25
## 43     883   H_40_44     2
## 44     884   H_40_44     0
## 45     888   H_40_44     6
## 46     001   H_45_49    55
## 47     343   H_45_49    17
## 48     883   H_45_49     4
## 49     884   H_45_49     1
## 50     888   H_45_49     3
## 51     001   H_50_54    43
## 52     343   H_50_54    19
## 53     883   H_50_54     3
## 54     884   H_50_54     0
## 55     888   H_50_54     3
## 56     001   H_55_59    44
## 57     343   H_55_59    22
## 58     883   H_55_59     6
## 59     884   H_55_59     0
## 60     888   H_55_59     1
## 61     001   H_60_64    30
## 62     343   H_60_64    12
## 63     883   H_60_64     1
## 64     884   H_60_64     0
## 65     888   H_60_64     1
## 66     001   H_65_69    15
## 67     343   H_65_69     9
## 68     883   H_65_69     1
## 69     884   H_65_69     0
## 70     888   H_65_69     3
## 71     001   H_70_74    14
## 72     343   H_70_74     7
## 73     883   H_70_74     2
## 74     884   H_70_74     0
## 75     888   H_70_74     1
## 76     001   H_75_79     7
## 77     343   H_75_79     3
## 78     883   H_75_79     0
## 79     884   H_75_79     0
## 80     888   H_75_79     1
## 81     001   H_80_84     2
## 82     343   H_80_84     2
## 83     883   H_80_84     1
## 84     884   H_80_84     0
## 85     888   H_80_84     0
## 86     001   H_85_89     2
## 87     343   H_85_89     0
## 88     883   H_85_89     0
## 89     884   H_85_89     0
## 90     888   H_85_89     0
## 91     001   H_90_94     1
## 92     343   H_90_94     0
## 93     883   H_90_94     0
## 94     884   H_90_94     0
## 95     888   H_90_94     0
## 96     001   H_95_99     1
## 97     343   H_95_99     1
## 98     883   H_95_99     0
## 99     884   H_95_99     0
## 100    888   H_95_99     0
## 101    001 H_100_104     0
## 102    343 H_100_104     0
## 103    883 H_100_104     0
## 104    884 H_100_104     0
## 105    888 H_100_104     0
## 106    001   M_00_04   134
## 107    343   M_00_04    52
## 108    883   M_00_04     6
## 109    884   M_00_04     0
## 110    888   M_00_04    11
## 111    001   M_05_09   137
## 112    343   M_05_09    58
## 113    883   M_05_09    17
## 114    884   M_05_09     0
## 115    888   M_05_09    12
## 116    001   M_10_14   128
## 117    343   M_10_14    42
## 118    883   M_10_14    28
## 119    884   M_10_14     0
## 120    888   M_10_14     6
## 121    001   M_15_19   152
## 122    343   M_15_19    53
## 123    883   M_15_19    21
## 124    884   M_15_19     1
## 125    888   M_15_19     5
## 126    001   M_20_24   104
## 127    343   M_20_24    54
## 128    883   M_20_24     4
## 129    884   M_20_24     2
## 130    888   M_20_24     3
## 131    001   M_25_29   100
## 132    343   M_25_29    39
## 133    883   M_25_29    10
## 134    884   M_25_29     2
## 135    888   M_25_29     8
## 136    001   M_30_34    64
## 137    343   M_30_34    26
## 138    883   M_30_34     3
## 139    884   M_30_34     0
## 140    888   M_30_34     4
## 141    001   M_35_39    70
## 142    343   M_35_39    22
## 143    883   M_35_39     7
## 144    884   M_35_39     0
## 145    888   M_35_39     5
## 146    001   M_40_44    40
## 147    343   M_40_44    24
## 148    883   M_40_44     5
## 149    884   M_40_44     1
## 150    888   M_40_44     3
## 151    001   M_45_49    45
## 152    343   M_45_49    13
## 153    883   M_45_49     2
## 154    884   M_45_49     0
## 155    888   M_45_49     2
## 156    001   M_50_54    38
## 157    343   M_50_54    17
## 158    883   M_50_54     2
## 159    884   M_50_54     0
## 160    888   M_50_54     1
## 161    001   M_55_59    25
## 162    343   M_55_59    15
## 163    883   M_55_59     3
## 164    884   M_55_59     0
## 165    888   M_55_59     4
## 166    001   M_60_64    20
## 167    343   M_60_64     2
## 168    883   M_60_64     1
## 169    884   M_60_64     0
## 170    888   M_60_64     1
## 171    001   M_65_69    12
## 172    343   M_65_69     4
## 173    883   M_65_69     0
## 174    884   M_65_69     0
## 175    888   M_65_69     4
## 176    001   M_70_74    11
## 177    343   M_70_74     1
## 178    883   M_70_74     0
## 179    884   M_70_74     0
## 180    888   M_70_74     1
## 181    001   M_75_79     9
## 182    343   M_75_79     4
## 183    883   M_75_79     0
## 184    884   M_75_79     0
## 185    888   M_75_79     0
## 186    001   M_80_84     4
## 187    343   M_80_84     0
## 188    883   M_80_84     2
## 189    884   M_80_84     0
## 190    888   M_80_84     0
## 191    001   M_85_89     0
## 192    343   M_85_89     0
## 193    883   M_85_89     0
## 194    884   M_85_89     0
## 195    888   M_85_89     0
## 196    001   M_90_94     0
## 197    343   M_90_94     0
## 198    883   M_90_94     0
## 199    884   M_90_94     0
## 200    888   M_90_94     0
## 201    001   M_95_99     2
## 202    343   M_95_99     0
## 203    883   M_95_99     0
## 204    884   M_95_99     0
## 205    888   M_95_99     0
## 206    001 M_100_104     1
## 207    343 M_100_104     0
## 208    883 M_100_104     0
## 209    884 M_100_104     0
## 210    888 M_100_104     0
# Crear columna 'Sexo' a partir de los primeros caracteres de la columna 'variable'
poblacioncp$Sexo <- as.factor(substr(poblacioncp$variable, start = 1, stop = 1))

# Crear columna 'Gquinquenal' a partir de los caracteres 3 a 8 de la columna 'variable'
poblacioncp$Gquinquenal <- substr(poblacioncp$variable, start = 3, stop = 9)

# Verificar si la columna 'Gquinquenal' existe antes de convertirla en factor
if("Gquinquenal" %in% colnames(poblacioncp)) {
  poblacioncp$Gquinquenal <- factor(poblacioncp$Gquinquenal, 
                                    levels = c("00_04", "05_09", "10_14", "15_19", "20_24", 
                                               "25_29", "30_34", "35_39", "40_44", "45_49", 
                                               "50_54", "55_59", "60_64", "65_69", "70_74", 
                                               "75_79", "80_84", "85_89", "90_94", "95_99", 
                                               "100_104"), 
                                    ordered = TRUE)
} else {
  stop("La columna 'Gquinquenal' no existe en el dataframe.")
}

# Asegúrate de que la columna 'value' sea numérica
poblacioncp$value <- as.numeric(as.character(poblacioncp$value))

# Agrupar y sumar
pop_cp <- poblacioncp %>%
  group_by(Gquinquenal, Sexo) %>%
  summarise(value = sum(value, na.rm = TRUE)) %>%  # Sumar los valores numéricos
  select(Gquinquenal, Sexo, value)
## `summarise()` has grouped output by 'Gquinquenal'. You can override using the
## `.groups` argument.
# Verifica el resultado
print(pop_cp)
## # A tibble: 42 × 3
## # Groups:   Gquinquenal [21]
##    Gquinquenal Sexo  value
##    <ord>       <fct> <dbl>
##  1 00_04       H       206
##  2 00_04       M       203
##  3 05_09       H       253
##  4 05_09       M       224
##  5 10_14       H       233
##  6 10_14       M       204
##  7 15_19       H       212
##  8 15_19       M       232
##  9 20_24       H       190
## 10 20_24       M       167
## # ℹ 32 more rows
poblacioncp <- poblacioncp[, c(3:5)]  # Seleccionar solo las columnas 3 a 5
poblacioncp <- poblacioncp[, c(3, 2, 1)]  # Reorganizar el orden de las columnas
print(poblacioncp)
##     Gquinquenal Sexo value
## 1         00_04    H   140
## 2         00_04    H    54
## 3         00_04    H     5
## 4         00_04    H     0
## 5         00_04    H     7
## 6         05_09    H   162
## 7         05_09    H    65
## 8         05_09    H    17
## 9         05_09    H     0
## 10        05_09    H     9
## 11        10_14    H   136
## 12        10_14    H    48
## 13        10_14    H    36
## 14        10_14    H     0
## 15        10_14    H    13
## 16        15_19    H   116
## 17        15_19    H    55
## 18        15_19    H    33
## 19        15_19    H     0
## 20        15_19    H     8
## 21        20_24    H   109
## 22        20_24    H    60
## 23        20_24    H    12
## 24        20_24    H     2
## 25        20_24    H     7
## 26        25_29    H    79
## 27        25_29    H    40
## 28        25_29    H     8
## 29        25_29    H     0
## 30        25_29    H     7
## 31        30_34    H    72
## 32        30_34    H    28
## 33        30_34    H     4
## 34        30_34    H     1
## 35        30_34    H     4
## 36        35_39    H    91
## 37        35_39    H    19
## 38        35_39    H     3
## 39        35_39    H     1
## 40        35_39    H     8
## 41        40_44    H    56
## 42        40_44    H    25
## 43        40_44    H     2
## 44        40_44    H     0
## 45        40_44    H     6
## 46        45_49    H    55
## 47        45_49    H    17
## 48        45_49    H     4
## 49        45_49    H     1
## 50        45_49    H     3
## 51        50_54    H    43
## 52        50_54    H    19
## 53        50_54    H     3
## 54        50_54    H     0
## 55        50_54    H     3
## 56        55_59    H    44
## 57        55_59    H    22
## 58        55_59    H     6
## 59        55_59    H     0
## 60        55_59    H     1
## 61        60_64    H    30
## 62        60_64    H    12
## 63        60_64    H     1
## 64        60_64    H     0
## 65        60_64    H     1
## 66        65_69    H    15
## 67        65_69    H     9
## 68        65_69    H     1
## 69        65_69    H     0
## 70        65_69    H     3
## 71        70_74    H    14
## 72        70_74    H     7
## 73        70_74    H     2
## 74        70_74    H     0
## 75        70_74    H     1
## 76        75_79    H     7
## 77        75_79    H     3
## 78        75_79    H     0
## 79        75_79    H     0
## 80        75_79    H     1
## 81        80_84    H     2
## 82        80_84    H     2
## 83        80_84    H     1
## 84        80_84    H     0
## 85        80_84    H     0
## 86        85_89    H     2
## 87        85_89    H     0
## 88        85_89    H     0
## 89        85_89    H     0
## 90        85_89    H     0
## 91        90_94    H     1
## 92        90_94    H     0
## 93        90_94    H     0
## 94        90_94    H     0
## 95        90_94    H     0
## 96        95_99    H     1
## 97        95_99    H     1
## 98        95_99    H     0
## 99        95_99    H     0
## 100       95_99    H     0
## 101     100_104    H     0
## 102     100_104    H     0
## 103     100_104    H     0
## 104     100_104    H     0
## 105     100_104    H     0
## 106       00_04    M   134
## 107       00_04    M    52
## 108       00_04    M     6
## 109       00_04    M     0
## 110       00_04    M    11
## 111       05_09    M   137
## 112       05_09    M    58
## 113       05_09    M    17
## 114       05_09    M     0
## 115       05_09    M    12
## 116       10_14    M   128
## 117       10_14    M    42
## 118       10_14    M    28
## 119       10_14    M     0
## 120       10_14    M     6
## 121       15_19    M   152
## 122       15_19    M    53
## 123       15_19    M    21
## 124       15_19    M     1
## 125       15_19    M     5
## 126       20_24    M   104
## 127       20_24    M    54
## 128       20_24    M     4
## 129       20_24    M     2
## 130       20_24    M     3
## 131       25_29    M   100
## 132       25_29    M    39
## 133       25_29    M    10
## 134       25_29    M     2
## 135       25_29    M     8
## 136       30_34    M    64
## 137       30_34    M    26
## 138       30_34    M     3
## 139       30_34    M     0
## 140       30_34    M     4
## 141       35_39    M    70
## 142       35_39    M    22
## 143       35_39    M     7
## 144       35_39    M     0
## 145       35_39    M     5
## 146       40_44    M    40
## 147       40_44    M    24
## 148       40_44    M     5
## 149       40_44    M     1
## 150       40_44    M     3
## 151       45_49    M    45
## 152       45_49    M    13
## 153       45_49    M     2
## 154       45_49    M     0
## 155       45_49    M     2
## 156       50_54    M    38
## 157       50_54    M    17
## 158       50_54    M     2
## 159       50_54    M     0
## 160       50_54    M     1
## 161       55_59    M    25
## 162       55_59    M    15
## 163       55_59    M     3
## 164       55_59    M     0
## 165       55_59    M     4
## 166       60_64    M    20
## 167       60_64    M     2
## 168       60_64    M     1
## 169       60_64    M     0
## 170       60_64    M     1
## 171       65_69    M    12
## 172       65_69    M     4
## 173       65_69    M     0
## 174       65_69    M     0
## 175       65_69    M     4
## 176       70_74    M    11
## 177       70_74    M     1
## 178       70_74    M     0
## 179       70_74    M     0
## 180       70_74    M     1
## 181       75_79    M     9
## 182       75_79    M     4
## 183       75_79    M     0
## 184       75_79    M     0
## 185       75_79    M     0
## 186       80_84    M     4
## 187       80_84    M     0
## 188       80_84    M     2
## 189       80_84    M     0
## 190       80_84    M     0
## 191       85_89    M     0
## 192       85_89    M     0
## 193       85_89    M     0
## 194       85_89    M     0
## 195       85_89    M     0
## 196       90_94    M     0
## 197       90_94    M     0
## 198       90_94    M     0
## 199       90_94    M     0
## 200       90_94    M     0
## 201       95_99    M     2
## 202       95_99    M     0
## 203       95_99    M     0
## 204       95_99    M     0
## 205       95_99    M     0
## 206     100_104    M     1
## 207     100_104    M     0
## 208     100_104    M     0
## 209     100_104    M     0
## 210     100_104    M     0
# Reestructuración para tener 'Hombres' y 'Mujeres' en columnas separadas
poblacioncp <- reshape(data = poblacioncp,
                       idvar = "Gquinquenal",
                       v.names = c("value"),
                       timevar = "Sexo",
                       direction = "wide")
## Warning in reshapeWide(data, idvar = idvar, timevar = timevar, varying =
## varying, : multiple rows match for Sexo=H: first taken
## Warning in reshapeWide(data, idvar = idvar, timevar = timevar, varying =
## varying, : multiple rows match for Sexo=M: first taken
# Verificar el nombre de las columnas
print(colnames(poblacioncp))
## [1] "Gquinquenal" "value.H"     "value.M"
# Renombrar columnas
poblacioncp <- poblacioncp %>%
  rename(Hombres = value.H, Mujeres = value.M)

# Calcular la población total
poblacioncp$Poblacion <- poblacioncp$Hombres + poblacioncp$Mujeres
print(poblacioncp)
##     Gquinquenal Hombres Mujeres Poblacion
## 1         00_04     140     134       274
## 6         05_09     162     137       299
## 11        10_14     136     128       264
## 16        15_19     116     152       268
## 21        20_24     109     104       213
## 26        25_29      79     100       179
## 31        30_34      72      64       136
## 36        35_39      91      70       161
## 41        40_44      56      40        96
## 46        45_49      55      45       100
## 51        50_54      43      38        81
## 56        55_59      44      25        69
## 61        60_64      30      20        50
## 66        65_69      15      12        27
## 71        70_74      14      11        25
## 76        75_79       7       9        16
## 81        80_84       2       4         6
## 86        85_89       2       0         2
## 91        90_94       1       0         1
## 96        95_99       1       2         3
## 101     100_104       0       1         1
# Procesar los datos para el gráfico
pop_cp <- poblacioncp %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH) * 100,
         Mujeres = (Mujeres / totM) * 100) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Calcular la población total para obtener proporciones sin multiplicar por 100
pop_cp <- poblacioncp %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH),   # Sin multiplicar por 100
         Mujeres = (Mujeres / totM)) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Gráfico de pirámide poblacional centros poblados en proporciones
ggplot(pop_cp, aes(x = Gquinquenal, y = `Poblacion por Sexo`, fill = Sexo)) +
  
  # Sección de HOMBRES (en proporciones negativas)
  geom_bar(data = subset(pop_cp, Sexo == "Hombres") %>% 
             mutate(`Poblacion por Sexo` = -`Poblacion por Sexo`),
           stat = "identity", width = 0.5, fill = "blue") +
  
  # Sección de MUJERES
  geom_bar(data = subset(pop_cp, Sexo == "Mujeres"),
           stat = "identity", width = 0.5, fill = "pink") +
  
  # Cambio de coordenadas para hacer horizontal
  coord_flip() +
  
  # Tema y estilos gráficos
  ggthemes::theme_tufte() +
  theme(plot.title = element_text(hjust = 0.5, size = 20),
        axis.text.x = element_text(),
        axis.text.y = element_text()) +
  
  # Etiquetas del gráfico
  labs(title = "Pirámide Poblacional Centros Poblados, 2018",
       x = "",
       y = "Hombres                        Mujeres",
       caption = "Fuente: DANE. \nCNPV 2018. Tabulados de Población") +
  
  # Escala de proporciones en el eje Y, ajustada en intervalos de 0.02
  scale_y_continuous(breaks = seq(-0.12, 0.12, by = 0.02),  # Proporciones en vez de porcentajes
                     labels = paste0(c(seq(0.12, 0, by = -0.02), seq(0.02, 0.12, by = 0.02))))

La pirámide poblacional de centros poblados del departamento de Guainía presenta un comportamiento diferente frente a las otras pirámides, debido a que se ve un incremento significativo de las mijeres frente a los hombres en edades económicamente activas, que cambia solo hasta el grupo etareo de 30 a 34 años, pues en adelante predomina principalmente la presencia de los hombres en los centros poblados.

Pirámide porcentual Rural Disperso

Este código analiza la población en zonas rurales dispersas y genera una pirámide poblacional, mostrando la proporción de hombres y mujeres por grupos de edad. A continuación te explico los pasos principales de manera simple:

Selección y filtrado de datos:

Se seleccionan las columnas relevantes del dataframe tabla_PersonaHogar y se filtran los registros que corresponden a áreas rurales dispersas (UA_CLASE == 3). Reestructuración de datos:

El dataframe se convierte a formato largo, con nuevas columnas creadas para identificar el sexo y los grupos de edad (quinquenios). Agrupación y suma:

La población se agrupa por quinquenios y sexo, sumando el total de personas en cada categoría. Reestructuración de hombres y mujeres en columnas separadas:

Se reorganiza el dataframe para que las columnas “Hombres” y “Mujeres” estén separadas, y se calcula la población total por quinquenio. Cálculo de proporciones:

Se calculan las proporciones de hombres y mujeres respecto al total de población en cada grupo de edad, expresadas como proporciones (sin multiplicar por 100). Creación de la pirámide poblacional:

Utilizando ggplot, se genera un gráfico de pirámide que muestra las proporciones de hombres y mujeres por quinquenios. Los hombres se representan con valores negativos para hacer más visual la comparación. Estilo y presentación del gráfico:

El gráfico se ajusta con estilo personalizado, utilizando colores diferentes para hombres y mujeres, con etiquetas claras y una escala de proporciones.

# Seleccionar columnas de la 2 a la 45
poblacionrd <- tabla_PersonaHogar[, 2:45]  
print(poblacionrd)  # Verifica el dataframe
##    U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1     001        1     949     994     995    1062    1091     818     726
## 2     001        2     140     162     136     116     109      79      72
## 3     001        3     343     879     895     685     451     250     226
## 4     343        2      54      65      48      55      60      40      28
## 5     343        3     357     708     662     555     343     166     114
## 6     883        2       5      17      36      33      12       8       4
## 7     883        3      48     111      93      59      49      36      30
## 8     884        2       0       0       0       0       2       0       1
## 9     884        3      68     152     129     148      54      40      44
## 10    888        2       7       9      13       8       7       7       4
## 11    888        3      33      58      53      59      31      16      22
##    H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1      637     528     520     415     368     225     155     140      91
## 2       91      56      55      43      44      30      15      14       7
## 3      232     162     112     113     117      71      51      34      22
## 4       19      25      17      19      22      12       9       7       3
## 5      102      79      90      67      55      17      25      19       7
## 6        3       2       4       3       6       1       1       2       0
## 7       38      37      27      20      11      15       9       5       5
## 8        1       0       1       0       0       0       0       0       0
## 9       37      43      35      33      22      17      13      13       2
## 10       8       6       3       3       1       1       3       1       1
## 11      13      13       6      13      11       3       2       2       3
##    H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1       32      21       3       3         2     913     962     973    1002
## 2        2       2       1       1         0     134     137     128     152
## 3       12       5       1       0         1     321     869     705     555
## 4        2       0       0       1         0      52      58      42      53
## 5        5       3       2       0         1     320     722     634     386
## 6        1       0       0       0         0       6      17      28      21
## 7        2       1       1       0         0      66      99      90      66
## 8        0       0       0       0         0       0       0       0       1
## 9        4       2       0       1         0      61     175     134      79
## 10       0       0       0       0         0      11      12       6       5
## 11       1       1       0       0         0      35      57      69      40
##    M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1      978     852     725     711     593     495     425     326     200
## 2      104     100      64      70      40      45      38      25      20
## 3      263     223     184     143     140      87     100      96      40
## 4       54      39      26      22      24      13      17      15       2
## 5      212     143     110      90      81      68      46      42      15
## 6        4      10       3       7       5       2       2       3       1
## 7       41      37      37      20      25      23      22      10      12
## 8        2       2       0       0       1       0       0       0       0
## 9       53      45      36      39      30      36      18      14      11
## 10       3       8       4       5       3       2       1       4       1
## 11      30      17      15      17      14       1       9       4       2
##    M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      153     105      81      30      18       8       1         0
## 2       12      11       9       4       0       0       2         1
## 3       42      33      22      12       5       1       3         1
## 4        4       1       4       0       0       0       0         0
## 5       19      16       7       4       2       1       0         0
## 6        0       0       0       2       0       0       0         0
## 7        6       5       3       1       1       1       0         0
## 8        0       0       0       0       0       0       0         0
## 9       16      14       8       2       2       0       0         2
## 10       4       1       0       0       0       0       0         0
## 11       3       4       0       1       1       0       1         0
# Filtrar solo donde UA_CLASE == 3 (Rural disperso)
poblacionrd <- poblacionrd %>%
  filter(UA_CLASE == 3)  
print(poblacionrd)  # Verifica los datos después de filtrar
##   U_MPIO UA_CLASE H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34
## 1    001        3     343     879     895     685     451     250     226
## 2    343        3     357     708     662     555     343     166     114
## 3    883        3      48     111      93      59      49      36      30
## 4    884        3      68     152     129     148      54      40      44
## 5    888        3      33      58      53      59      31      16      22
##   H_35_39 H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79
## 1     232     162     112     113     117      71      51      34      22
## 2     102      79      90      67      55      17      25      19       7
## 3      38      37      27      20      11      15       9       5       5
## 4      37      43      35      33      22      17      13      13       2
## 5      13      13       6      13      11       3       2       2       3
##   H_80_84 H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19
## 1      12       5       1       0         1     321     869     705     555
## 2       5       3       2       0         1     320     722     634     386
## 3       2       1       1       0         0      66      99      90      66
## 4       4       2       0       1         0      61     175     134      79
## 5       1       1       0       0         0      35      57      69      40
##   M_20_24 M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64
## 1     263     223     184     143     140      87     100      96      40
## 2     212     143     110      90      81      68      46      42      15
## 3      41      37      37      20      25      23      22      10      12
## 4      53      45      36      39      30      36      18      14      11
## 5      30      17      15      17      14       1       9       4       2
##   M_65_69 M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      42      33      22      12       5       1       3         1
## 2      19      16       7       4       2       1       0         0
## 3       6       5       3       1       1       1       0         0
## 4      16      14       8       2       2       0       0         2
## 5       3       4       0       1       1       0       1         0
# Eliminar la segunda columna
poblacionrd <- poblacionrd[,-c(2)]  
print(poblacionrd)  # Verifica el dataframe sin la columna
##   U_MPIO H_00_04 H_05_09 H_10_14 H_15_19 H_20_24 H_25_29 H_30_34 H_35_39
## 1    001     343     879     895     685     451     250     226     232
## 2    343     357     708     662     555     343     166     114     102
## 3    883      48     111      93      59      49      36      30      38
## 4    884      68     152     129     148      54      40      44      37
## 5    888      33      58      53      59      31      16      22      13
##   H_40_44 H_45_49 H_50_54 H_55_59 H_60_64 H_65_69 H_70_74 H_75_79 H_80_84
## 1     162     112     113     117      71      51      34      22      12
## 2      79      90      67      55      17      25      19       7       5
## 3      37      27      20      11      15       9       5       5       2
## 4      43      35      33      22      17      13      13       2       4
## 5      13       6      13      11       3       2       2       3       1
##   H_85_89 H_90_94 H_95_99 H_100_104 M_00_04 M_05_09 M_10_14 M_15_19 M_20_24
## 1       5       1       0         1     321     869     705     555     263
## 2       3       2       0         1     320     722     634     386     212
## 3       1       1       0         0      66      99      90      66      41
## 4       2       0       1         0      61     175     134      79      53
## 5       1       0       0         0      35      57      69      40      30
##   M_25_29 M_30_34 M_35_39 M_40_44 M_45_49 M_50_54 M_55_59 M_60_64 M_65_69
## 1     223     184     143     140      87     100      96      40      42
## 2     143     110      90      81      68      46      42      15      19
## 3      37      37      20      25      23      22      10      12       6
## 4      45      36      39      30      36      18      14      11      16
## 5      17      15      17      14       1       9       4       2       3
##   M_70_74 M_75_79 M_80_84 M_85_89 M_90_94 M_95_99 M_100_104
## 1      33      22      12       5       1       3         1
## 2      16       7       4       2       1       0         0
## 3       5       3       1       1       1       0         0
## 4      14       8       2       2       0       0         2
## 5       4       0       1       1       0       1         0
# Convertir el dataframe a formato largo
poblacionrd <- melt(poblacionrd, id.vars = "U_MPIO")  
print(poblacionrd)
##     U_MPIO  variable value
## 1      001   H_00_04   343
## 2      343   H_00_04   357
## 3      883   H_00_04    48
## 4      884   H_00_04    68
## 5      888   H_00_04    33
## 6      001   H_05_09   879
## 7      343   H_05_09   708
## 8      883   H_05_09   111
## 9      884   H_05_09   152
## 10     888   H_05_09    58
## 11     001   H_10_14   895
## 12     343   H_10_14   662
## 13     883   H_10_14    93
## 14     884   H_10_14   129
## 15     888   H_10_14    53
## 16     001   H_15_19   685
## 17     343   H_15_19   555
## 18     883   H_15_19    59
## 19     884   H_15_19   148
## 20     888   H_15_19    59
## 21     001   H_20_24   451
## 22     343   H_20_24   343
## 23     883   H_20_24    49
## 24     884   H_20_24    54
## 25     888   H_20_24    31
## 26     001   H_25_29   250
## 27     343   H_25_29   166
## 28     883   H_25_29    36
## 29     884   H_25_29    40
## 30     888   H_25_29    16
## 31     001   H_30_34   226
## 32     343   H_30_34   114
## 33     883   H_30_34    30
## 34     884   H_30_34    44
## 35     888   H_30_34    22
## 36     001   H_35_39   232
## 37     343   H_35_39   102
## 38     883   H_35_39    38
## 39     884   H_35_39    37
## 40     888   H_35_39    13
## 41     001   H_40_44   162
## 42     343   H_40_44    79
## 43     883   H_40_44    37
## 44     884   H_40_44    43
## 45     888   H_40_44    13
## 46     001   H_45_49   112
## 47     343   H_45_49    90
## 48     883   H_45_49    27
## 49     884   H_45_49    35
## 50     888   H_45_49     6
## 51     001   H_50_54   113
## 52     343   H_50_54    67
## 53     883   H_50_54    20
## 54     884   H_50_54    33
## 55     888   H_50_54    13
## 56     001   H_55_59   117
## 57     343   H_55_59    55
## 58     883   H_55_59    11
## 59     884   H_55_59    22
## 60     888   H_55_59    11
## 61     001   H_60_64    71
## 62     343   H_60_64    17
## 63     883   H_60_64    15
## 64     884   H_60_64    17
## 65     888   H_60_64     3
## 66     001   H_65_69    51
## 67     343   H_65_69    25
## 68     883   H_65_69     9
## 69     884   H_65_69    13
## 70     888   H_65_69     2
## 71     001   H_70_74    34
## 72     343   H_70_74    19
## 73     883   H_70_74     5
## 74     884   H_70_74    13
## 75     888   H_70_74     2
## 76     001   H_75_79    22
## 77     343   H_75_79     7
## 78     883   H_75_79     5
## 79     884   H_75_79     2
## 80     888   H_75_79     3
## 81     001   H_80_84    12
## 82     343   H_80_84     5
## 83     883   H_80_84     2
## 84     884   H_80_84     4
## 85     888   H_80_84     1
## 86     001   H_85_89     5
## 87     343   H_85_89     3
## 88     883   H_85_89     1
## 89     884   H_85_89     2
## 90     888   H_85_89     1
## 91     001   H_90_94     1
## 92     343   H_90_94     2
## 93     883   H_90_94     1
## 94     884   H_90_94     0
## 95     888   H_90_94     0
## 96     001   H_95_99     0
## 97     343   H_95_99     0
## 98     883   H_95_99     0
## 99     884   H_95_99     1
## 100    888   H_95_99     0
## 101    001 H_100_104     1
## 102    343 H_100_104     1
## 103    883 H_100_104     0
## 104    884 H_100_104     0
## 105    888 H_100_104     0
## 106    001   M_00_04   321
## 107    343   M_00_04   320
## 108    883   M_00_04    66
## 109    884   M_00_04    61
## 110    888   M_00_04    35
## 111    001   M_05_09   869
## 112    343   M_05_09   722
## 113    883   M_05_09    99
## 114    884   M_05_09   175
## 115    888   M_05_09    57
## 116    001   M_10_14   705
## 117    343   M_10_14   634
## 118    883   M_10_14    90
## 119    884   M_10_14   134
## 120    888   M_10_14    69
## 121    001   M_15_19   555
## 122    343   M_15_19   386
## 123    883   M_15_19    66
## 124    884   M_15_19    79
## 125    888   M_15_19    40
## 126    001   M_20_24   263
## 127    343   M_20_24   212
## 128    883   M_20_24    41
## 129    884   M_20_24    53
## 130    888   M_20_24    30
## 131    001   M_25_29   223
## 132    343   M_25_29   143
## 133    883   M_25_29    37
## 134    884   M_25_29    45
## 135    888   M_25_29    17
## 136    001   M_30_34   184
## 137    343   M_30_34   110
## 138    883   M_30_34    37
## 139    884   M_30_34    36
## 140    888   M_30_34    15
## 141    001   M_35_39   143
## 142    343   M_35_39    90
## 143    883   M_35_39    20
## 144    884   M_35_39    39
## 145    888   M_35_39    17
## 146    001   M_40_44   140
## 147    343   M_40_44    81
## 148    883   M_40_44    25
## 149    884   M_40_44    30
## 150    888   M_40_44    14
## 151    001   M_45_49    87
## 152    343   M_45_49    68
## 153    883   M_45_49    23
## 154    884   M_45_49    36
## 155    888   M_45_49     1
## 156    001   M_50_54   100
## 157    343   M_50_54    46
## 158    883   M_50_54    22
## 159    884   M_50_54    18
## 160    888   M_50_54     9
## 161    001   M_55_59    96
## 162    343   M_55_59    42
## 163    883   M_55_59    10
## 164    884   M_55_59    14
## 165    888   M_55_59     4
## 166    001   M_60_64    40
## 167    343   M_60_64    15
## 168    883   M_60_64    12
## 169    884   M_60_64    11
## 170    888   M_60_64     2
## 171    001   M_65_69    42
## 172    343   M_65_69    19
## 173    883   M_65_69     6
## 174    884   M_65_69    16
## 175    888   M_65_69     3
## 176    001   M_70_74    33
## 177    343   M_70_74    16
## 178    883   M_70_74     5
## 179    884   M_70_74    14
## 180    888   M_70_74     4
## 181    001   M_75_79    22
## 182    343   M_75_79     7
## 183    883   M_75_79     3
## 184    884   M_75_79     8
## 185    888   M_75_79     0
## 186    001   M_80_84    12
## 187    343   M_80_84     4
## 188    883   M_80_84     1
## 189    884   M_80_84     2
## 190    888   M_80_84     1
## 191    001   M_85_89     5
## 192    343   M_85_89     2
## 193    883   M_85_89     1
## 194    884   M_85_89     2
## 195    888   M_85_89     1
## 196    001   M_90_94     1
## 197    343   M_90_94     1
## 198    883   M_90_94     1
## 199    884   M_90_94     0
## 200    888   M_90_94     0
## 201    001   M_95_99     3
## 202    343   M_95_99     0
## 203    883   M_95_99     0
## 204    884   M_95_99     0
## 205    888   M_95_99     1
## 206    001 M_100_104     1
## 207    343 M_100_104     0
## 208    883 M_100_104     0
## 209    884 M_100_104     2
## 210    888 M_100_104     0
# Crear columna 'Sexo' a partir de los primeros caracteres de la columna 'variable'
poblacionrd$Sexo <- as.factor(substr(poblacionrd$variable, start = 1, stop = 1))

# Crear columna 'Gquinquenal' a partir de los caracteres 3 a 8 de la columna 'variable'
poblacionrd$Gquinquenal <- substr(poblacionrd$variable, start = 3, stop = 9)

# Verificar si la columna 'Gquinquenal' existe antes de convertirla en factor
if("Gquinquenal" %in% colnames(poblacionrd)) {
  poblacionrd$Gquinquenal <- factor(poblacionrd$Gquinquenal, 
                                    levels = c("00_04", "05_09", "10_14", "15_19", "20_24", 
                                               "25_29", "30_34", "35_39", "40_44", "45_49", 
                                               "50_54", "55_59", "60_64", "65_69", "70_74", 
                                               "75_79", "80_84", "85_89", "90_94", "95_99", 
                                               "100_104"), 
                                    ordered = TRUE)
} else {
  stop("La columna 'Gquinquenal' no existe en el dataframe.")
}

# Asegúrate de que la columna 'value' sea numérica
poblacionrd$value <- as.numeric(as.character(poblacionrd$value))

# Agrupar y sumar
pop_rd <- poblacionrd %>%
  group_by(Gquinquenal, Sexo) %>%
  summarise(value = sum(value, na.rm = TRUE)) %>%  # Sumar los valores numéricos
  select(Gquinquenal, Sexo, value)
## `summarise()` has grouped output by 'Gquinquenal'. You can override using the
## `.groups` argument.
# Verifica el resultado
print(pop_rd)
## # A tibble: 42 × 3
## # Groups:   Gquinquenal [21]
##    Gquinquenal Sexo  value
##    <ord>       <fct> <dbl>
##  1 00_04       H       849
##  2 00_04       M       803
##  3 05_09       H      1908
##  4 05_09       M      1922
##  5 10_14       H      1832
##  6 10_14       M      1632
##  7 15_19       H      1506
##  8 15_19       M      1126
##  9 20_24       H       928
## 10 20_24       M       599
## # ℹ 32 more rows
poblacionrd <- poblacionrd[, c(3:5)]  # Seleccionar solo las columnas 3 a 5
poblacionrd <- poblacionrd[, c(3, 2, 1)]  # Reorganizar el orden de las columnas
print(poblacionrd)
##     Gquinquenal Sexo value
## 1         00_04    H   343
## 2         00_04    H   357
## 3         00_04    H    48
## 4         00_04    H    68
## 5         00_04    H    33
## 6         05_09    H   879
## 7         05_09    H   708
## 8         05_09    H   111
## 9         05_09    H   152
## 10        05_09    H    58
## 11        10_14    H   895
## 12        10_14    H   662
## 13        10_14    H    93
## 14        10_14    H   129
## 15        10_14    H    53
## 16        15_19    H   685
## 17        15_19    H   555
## 18        15_19    H    59
## 19        15_19    H   148
## 20        15_19    H    59
## 21        20_24    H   451
## 22        20_24    H   343
## 23        20_24    H    49
## 24        20_24    H    54
## 25        20_24    H    31
## 26        25_29    H   250
## 27        25_29    H   166
## 28        25_29    H    36
## 29        25_29    H    40
## 30        25_29    H    16
## 31        30_34    H   226
## 32        30_34    H   114
## 33        30_34    H    30
## 34        30_34    H    44
## 35        30_34    H    22
## 36        35_39    H   232
## 37        35_39    H   102
## 38        35_39    H    38
## 39        35_39    H    37
## 40        35_39    H    13
## 41        40_44    H   162
## 42        40_44    H    79
## 43        40_44    H    37
## 44        40_44    H    43
## 45        40_44    H    13
## 46        45_49    H   112
## 47        45_49    H    90
## 48        45_49    H    27
## 49        45_49    H    35
## 50        45_49    H     6
## 51        50_54    H   113
## 52        50_54    H    67
## 53        50_54    H    20
## 54        50_54    H    33
## 55        50_54    H    13
## 56        55_59    H   117
## 57        55_59    H    55
## 58        55_59    H    11
## 59        55_59    H    22
## 60        55_59    H    11
## 61        60_64    H    71
## 62        60_64    H    17
## 63        60_64    H    15
## 64        60_64    H    17
## 65        60_64    H     3
## 66        65_69    H    51
## 67        65_69    H    25
## 68        65_69    H     9
## 69        65_69    H    13
## 70        65_69    H     2
## 71        70_74    H    34
## 72        70_74    H    19
## 73        70_74    H     5
## 74        70_74    H    13
## 75        70_74    H     2
## 76        75_79    H    22
## 77        75_79    H     7
## 78        75_79    H     5
## 79        75_79    H     2
## 80        75_79    H     3
## 81        80_84    H    12
## 82        80_84    H     5
## 83        80_84    H     2
## 84        80_84    H     4
## 85        80_84    H     1
## 86        85_89    H     5
## 87        85_89    H     3
## 88        85_89    H     1
## 89        85_89    H     2
## 90        85_89    H     1
## 91        90_94    H     1
## 92        90_94    H     2
## 93        90_94    H     1
## 94        90_94    H     0
## 95        90_94    H     0
## 96        95_99    H     0
## 97        95_99    H     0
## 98        95_99    H     0
## 99        95_99    H     1
## 100       95_99    H     0
## 101     100_104    H     1
## 102     100_104    H     1
## 103     100_104    H     0
## 104     100_104    H     0
## 105     100_104    H     0
## 106       00_04    M   321
## 107       00_04    M   320
## 108       00_04    M    66
## 109       00_04    M    61
## 110       00_04    M    35
## 111       05_09    M   869
## 112       05_09    M   722
## 113       05_09    M    99
## 114       05_09    M   175
## 115       05_09    M    57
## 116       10_14    M   705
## 117       10_14    M   634
## 118       10_14    M    90
## 119       10_14    M   134
## 120       10_14    M    69
## 121       15_19    M   555
## 122       15_19    M   386
## 123       15_19    M    66
## 124       15_19    M    79
## 125       15_19    M    40
## 126       20_24    M   263
## 127       20_24    M   212
## 128       20_24    M    41
## 129       20_24    M    53
## 130       20_24    M    30
## 131       25_29    M   223
## 132       25_29    M   143
## 133       25_29    M    37
## 134       25_29    M    45
## 135       25_29    M    17
## 136       30_34    M   184
## 137       30_34    M   110
## 138       30_34    M    37
## 139       30_34    M    36
## 140       30_34    M    15
## 141       35_39    M   143
## 142       35_39    M    90
## 143       35_39    M    20
## 144       35_39    M    39
## 145       35_39    M    17
## 146       40_44    M   140
## 147       40_44    M    81
## 148       40_44    M    25
## 149       40_44    M    30
## 150       40_44    M    14
## 151       45_49    M    87
## 152       45_49    M    68
## 153       45_49    M    23
## 154       45_49    M    36
## 155       45_49    M     1
## 156       50_54    M   100
## 157       50_54    M    46
## 158       50_54    M    22
## 159       50_54    M    18
## 160       50_54    M     9
## 161       55_59    M    96
## 162       55_59    M    42
## 163       55_59    M    10
## 164       55_59    M    14
## 165       55_59    M     4
## 166       60_64    M    40
## 167       60_64    M    15
## 168       60_64    M    12
## 169       60_64    M    11
## 170       60_64    M     2
## 171       65_69    M    42
## 172       65_69    M    19
## 173       65_69    M     6
## 174       65_69    M    16
## 175       65_69    M     3
## 176       70_74    M    33
## 177       70_74    M    16
## 178       70_74    M     5
## 179       70_74    M    14
## 180       70_74    M     4
## 181       75_79    M    22
## 182       75_79    M     7
## 183       75_79    M     3
## 184       75_79    M     8
## 185       75_79    M     0
## 186       80_84    M    12
## 187       80_84    M     4
## 188       80_84    M     1
## 189       80_84    M     2
## 190       80_84    M     1
## 191       85_89    M     5
## 192       85_89    M     2
## 193       85_89    M     1
## 194       85_89    M     2
## 195       85_89    M     1
## 196       90_94    M     1
## 197       90_94    M     1
## 198       90_94    M     1
## 199       90_94    M     0
## 200       90_94    M     0
## 201       95_99    M     3
## 202       95_99    M     0
## 203       95_99    M     0
## 204       95_99    M     0
## 205       95_99    M     1
## 206     100_104    M     1
## 207     100_104    M     0
## 208     100_104    M     0
## 209     100_104    M     2
## 210     100_104    M     0
# Reestructuración para tener 'Hombres' y 'Mujeres' en columnas separadas
poblacionrd <- reshape(data = poblacionrd,
                       idvar = "Gquinquenal",
                       v.names = c("value"),
                       timevar = "Sexo",
                       direction = "wide")
## Warning in reshapeWide(data, idvar = idvar, timevar = timevar, varying =
## varying, : multiple rows match for Sexo=H: first taken
## Warning in reshapeWide(data, idvar = idvar, timevar = timevar, varying =
## varying, : multiple rows match for Sexo=M: first taken
# Verificar el nombre de las columnas
print(colnames(poblacionrd))
## [1] "Gquinquenal" "value.H"     "value.M"
# Renombrar columnas
poblacionrd <- poblacionrd %>%
  rename(Hombres = value.H, Mujeres = value.M)

# Calcular la población total
poblacionrd$Poblacion <- poblacionrd$Hombres + poblacionrd$Mujeres
print(poblacionrd)
##     Gquinquenal Hombres Mujeres Poblacion
## 1         00_04     343     321       664
## 6         05_09     879     869      1748
## 11        10_14     895     705      1600
## 16        15_19     685     555      1240
## 21        20_24     451     263       714
## 26        25_29     250     223       473
## 31        30_34     226     184       410
## 36        35_39     232     143       375
## 41        40_44     162     140       302
## 46        45_49     112      87       199
## 51        50_54     113     100       213
## 56        55_59     117      96       213
## 61        60_64      71      40       111
## 66        65_69      51      42        93
## 71        70_74      34      33        67
## 76        75_79      22      22        44
## 81        80_84      12      12        24
## 86        85_89       5       5        10
## 91        90_94       1       1         2
## 96        95_99       0       3         3
## 101     100_104       1       1         2
# Procesar los datos para el gráfico
pop_rd <- poblacionrd %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH) * 100,
         Mujeres = (Mujeres / totM) * 100) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Calcular la población total para obtener proporciones sin multiplicar por 100
pop_rd <- poblacionrd %>%
  group_by(Gquinquenal) %>%
  summarise_all(sum, na.rm = TRUE) %>%
  mutate(totH = sum(Hombres), totM = sum(Mujeres)) %>%
  mutate(Hombres = (Hombres / totH),   # Sin multiplicar por 100
         Mujeres = (Mujeres / totM)) %>%
  select(-totH, -totM) %>%
  pivot_longer(cols = c("Hombres", "Mujeres"),
               names_to = "Sexo",
               values_to = "Poblacion por Sexo") %>%
  select(Gquinquenal, Sexo, Poblacion, `Poblacion por Sexo`)

# Gráfico de pirámide poblacional rural en proporciones
ggplot(pop_rd, aes(x = Gquinquenal, y = `Poblacion por Sexo`, fill = Sexo)) +
  
  # Sección de HOMBRES (en proporciones negativas)
  geom_bar(data = subset(pop_rd, Sexo == "Hombres") %>% 
             mutate(`Poblacion por Sexo` = -`Poblacion por Sexo`),
           stat = "identity", width = 0.5, fill = "blue") +
  
  # Sección de MUJERES
  geom_bar(data = subset(pop_rd, Sexo == "Mujeres"),
           stat = "identity", width = 0.5, fill = "pink") +
  
  # Cambio de coordenadas para hacer horizontal
  coord_flip() +
  
  # Tema y estilos gráficos
  ggthemes::theme_tufte() +
  theme(plot.title = element_text(hjust = 0.5, size = 20),
        axis.text.x = element_text(),
        axis.text.y = element_text()) +
  
  # Etiquetas del gráfico
  labs(title = "Pirámide Poblacional Rural Disperso, 2018",
       x = "",
       y = "Hombres                        Mujeres",
       caption = "Fuente: DANE. \nCNPV 2018. Tabulados de Población") +
  
  # Escala de proporciones en el eje Y, ajustada en intervalos de 0.02
  scale_y_continuous(breaks = seq(-0.12, 0.12, by = 0.02),  # Proporciones en vez de porcentajes
                     labels = paste0(c(seq(0.12, 0, by = -0.02), seq(0.02, 0.12, by = 0.02))))

En la pirámide poblacional del área rural dispersa, podemos observar que el primer grupo estareo quinquenal de 0 a 4 años es uni de los grupos más pequeños, lo que debe ser considerado para establecer mejores políticas públicas que mejoren la salud y desarrollo de los niños en edades de vida temprana. Además podemos apreciar una tendencia en la que desde el grupo quinquenal de 25 a 29 años la población disminuye y esto se mantiene hasta los grupos etareos más longevos.

Conclusión

Podemos concluir que en el departamento de Guainía existen diferencias significativas en el comportamiento de la población en la cabecera municipal, los centros poblados y el área rural dispersa.

En la cabecera urbana, la pirámide poblacional del municipio del departamento de Guainía en 2018, nos premite observar que la población se distribuye uniformemente en los primeros años de vida, sin embargo la presencia de los hombres es mayor desde el grupo etareo de 20 a 24 años. Después se vuelve a distribuir casi uniformemente la población, sin embargo en los grupos etareos más longevos se aprecia la presencia de la población masculina principalmente.

En los centros poblados, la pirámide poblacional del departamento de Guainía presenta un comportamiento diferente frente a las otras pirámides, debido a que se ve un incremento significativo de las mijeres frente a los hombres en edades económicamente activas, que cambia solo hasta el grupo etareo de 30 a 34 años, pues en adelante predomina principalmente la presencia de los hombres en los centros poblados.

Finalmente, en el área rural dispersa la pirámide poblacional del área nos muestra que el primer grupo estareo quinquenal de 0 a 4 años es uno de los grupos más pequeños, lo que debe ser considerado para establecer mejores políticas públicas que mejoren la salud y desarrollo de los niños en edades de vida temprana. Además podemos apreciar una tendencia en la que desde el grupo quinquenal de 25 a 29 años la población disminuye y esto se mantiene hasta los grupos etareos más longevos.

En conjunto, las tres pirámides destacan una población en la que en los grupos etareos mayores prevalece la presencia de hombres, además de que cuentan con una población joven en crecimiento, lo que permite que se puedan establecer políticas públicas que permitan beneficiar a los jovenes del departamento y se insentive su permanencia para el desarrollo del territorio.