<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>ARG</title>
<link>https://alejandroromerog.github.io/blog.html</link>
<atom:link href="https://alejandroromerog.github.io/blog.xml" rel="self" type="application/rss+xml"/>
<description></description>
<generator>quarto-1.4.549</generator>
<lastBuildDate>Tue, 02 Jun 2026 06:00:00 GMT</lastBuildDate>
<item>
  <title>Análisis de encuestas ENIF y ENAFIN</title>
  <link>https://alejandroromerog.github.io/blog/ENIF-ENAFIN/</link>
  <description><![CDATA[ 





<section id="introducción" class="level1">
<h1>Introducción</h1>
<p>Las encuestas oficiales son una de las fuentes más importantes para analizar fenómenos sociales y económicos, pero trabajar con ellas requiere más que solo abrir una base de datos y directamente calcular promedios. En este tutorial usaremos dos encuestas del Instituto Nacional de Estadística y Geografía (INEGI) relacionadas con el sistema financiero: la Encuesta Nacional de Inclusión Financiera (ENIF) y la Encuesta Nacional de Financiamiento de las Empresas (ENAFIN). A partir de ellas veremos cómo descargar sus datos abiertos, leer archivos CSV en R, construir variables de análisis, respetar el diseño muestral de una encuesta compleja con <code>{survey}</code> y <code>{srvyr}</code> y crear visualizaciones que comuniquen los resultados de forma clara.</p>
</section>
<section id="descarga-de-datos" class="level1">
<h1>Descarga de datos</h1>
<p>Antes de sumergirnos en el código, primero debemos obtener los datos. A continuación, te guiaré a través de los pasos para descargarlos del sitio oficial del INEGI. Cabe destacar que, en este tutorial, utilizaremos solamente las versiones de 2021 de ambas encuestas; sin embargo, el procedimiento es casi el mismo para cualquier edición de las mismas.</p>
<p>En primer lugar, debemos ir al <a href="https://www.inegi.org.mx/">sitio web del INEGI</a> y buscar las encuestas ENIF y ENAFIN. Para ello, podemos utilizar el buscador que aparece en la página principal o simplemente hacer clic en los siguientes enlaces:</p>
<ul>
<li><a href="https://www.inegi.org.mx/programas/enif/2021/#datos_abiertos">Encuesta Nacional de Inclusión Financiera 2021</a></li>
<li><a href="https://www.inegi.org.mx/programas/enafin/2021/#datos_abiertos">Encuesta Nacional de Financiamiento de las Empresas 2021</a></li>
</ul>
<p>Una vez que hayamos ingresado a la sección de <strong><em>Datos abiertos</em></strong> de cada encuesta, debemos cliquear estos botones que resalté con rectángulos rojos para iniciar las respectivas descargas:</p>
<div style="display: flex; justify-content: center; align-items: center;">
    <img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/ENIFDescarga.png" style="max-width: 55%; height: auto; margin-right: 2px;">
    <img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/ENAFINDescarga.png" style="max-width: 55%; height: auto; margin-left: 2px;">
</div>
<p><br></p>
<p>Ya completadas las descargas, encontraremos los archivos de ambas encuestas en nuestra computadora. Dichos archivos deben de verse así:</p>
<p><a href="CarpetaDescargas.png" class="lightbox" data-gallery="quarto-lightbox-gallery-1"><img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/CarpetaDescargas.png" class="img-fluid"></a></p>
<p>Los dos archivos vienen en formato comprimido (.zip). Para poder utilizar los datos, necesitamos descomprimirlos primero. Para ello, en Windows, podemos hacer clic derecho sobre cada archivo y seleccionar la opción <em>Extraer aquí;</em> en macOS solo basta con dar doble clic en cada uno de ellos. Al haber hecho esto, veremos que se crearán dos carpetas nuevas, una para cada encuesta, que contienen los archivos de datos, los diccionarios de variables y los modelos entidad-relación de las mismas:</p>
<div style="display: flex; justify-content: center; align-items: center; flex-direction: column;">
    <img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/CarpetaDescargas2.png" style="max-width: 59%; height: auto; margin-bottom: 2px;">

    <div style="display: flex; justify-content: center; align-items: center;">
        <img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/CarpetaDescargas3.png" style="max-width: 59%; height: auto; margin-right: 1px;">
        <img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/CarpetaDescargas4.png" style="max-width: 59%; height: auto; margin-left: 1px;">
    </div>
</div>
<p><br></p>
<p>Con los datos descomprimidos listos, el siguiente paso es cargarlos en R y empezar a trabajar con ellos.</p>
</section>
<section id="procesamiento-de-datos" class="level1">
<h1>Procesamiento de datos</h1>
<p>Para empezar con el código, debemos crear un nuevo archivo de R Markdown o Quarto. En RStudio, podemos ir a <em>File &gt; New File &gt; R Markdown…</em> o <em>File &gt; New File &gt; Quarto Document…</em>, según el formato que prefiramos. Para mantener las cosas simples, conviene guardar ese archivo en la misma carpeta donde descomprimimos los datos de ambas encuestas. De esta manera, R podrá encontrar los archivos usando rutas relativas, sin necesidad de escribir la ruta completa de nuestra computadora.</p>
<p>En lo que sigue asumiré que las carpetas descomprimidas conservan los nombres que vimos en las capturas de pantalla anteriores: <code>conjunto_de_datos_enif_2021_csv</code> para la ENIF y <code>enafin_2019_2021_csv</code> para la ENAFIN. Si tu computadora descomprimió los archivos de forma ligeramente distinta, solo tendrás que ajustar esas primeras partes de las rutas.</p>
<p>En este tutorial utilizaremos siete paquetes. Los primeros nos servirán para leer archivos, manipular datos y hacer gráficas. Los dos últimos, <code>{survey}</code> y <code>{srvyr}</code>, son especialmente importantes porque nos permiten trabajar correctamente con encuestas que tienen diseño muestral complejo:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Si aún no los tienes instalados, puedes usar:</span></span>
<span id="cb1-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># install.packages(c("readr", "dplyr", "tidyr", "ggplot2", "scales", "survey", "srvyr"))</span></span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(readr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para leer archivos CSV</span></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(dplyr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para manipular datos</span></span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(tidyr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para transformar bases de datos</span></span>
<span id="cb1-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para crear gráficas</span></span>
<span id="cb1-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(scales) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para formatear porcentajes en las gráficas</span></span>
<span id="cb1-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(survey) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para trabajar con diseños muestrales complejos</span></span>
<span id="cb1-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(srvyr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para usar survey con sintaxis parecida a dplyr</span></span></code></pre></div>
</div>
<p>La diferencia entre <code>{survey}</code> y <code>{srvyr}</code> no está en el objetivo, sino en la forma de escribir el código. <code>{survey}</code> es el paquete clásico para analizar encuestas complejas en R; <code>{srvyr}</code> construye sobre <code>{survey}</code> y permite escribir muchas de las mismas operaciones con una sintaxis más parecida a <code>{dplyr}</code>. En la práctica, conviene conocer ambos: <code>{survey}</code> es más general y muy usado en documentación técnica, mientras que <code>{srvyr}</code> resulta más cómodo cuando ya trabajamos con tuberías (<code>|&gt;</code> o <code>%&gt;%</code>), <code>group_by()</code> y <code>summarize()</code>.</p>
<section id="lectura-de-la-enif" class="level2">
<h2 class="anchored" data-anchor-id="lectura-de-la-enif">Lectura de la ENIF</h2>
<p>Comenzaremos con la ENIF. Dentro de los archivos descomprimidos hay varias tablas, pero para este ejemplo trabajaremos con la tabla del módulo principal, llamada <code>conjunto_de_datos_tmodulo_enif_2021.csv</code>. La podemos leer de la siguiente manera:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">ruta_enif <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(</span>
<span id="cb2-2">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"conjunto_de_datos_enif_2021_csv/"</span>,</span>
<span id="cb2-3">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"conjunto_de_datos_tmodulo_enif_2021/"</span>,</span>
<span id="cb2-4">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"conjunto_de_datos/"</span>,</span>
<span id="cb2-5">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"conjunto_de_datos_tmodulo_enif_2021.csv"</span></span>
<span id="cb2-6">)</span>
<span id="cb2-7"></span>
<span id="cb2-8">enif_tmodulo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_csv</span>(</span>
<span id="cb2-9">  ruta_enif,</span>
<span id="cb2-10">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">guess_max =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>,</span>
<span id="cb2-11">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">show_col_types =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb2-12">)</span></code></pre></div>
</div>
<p>En este caso usamos <code>guess_max = Inf</code> para que R revise todas las filas antes de decidir el tipo de cada columna. Esto evita que algunas variables codificadas con números se lean por error como variables lógicas (<code>TRUE</code>/<code>FALSE</code>). También usamos <code>show_col_types = FALSE</code> únicamente para ocultar el mensaje técnico que <code>{readr}</code> imprime al terminar la lectura.</p>
<p>Una vez importada la tabla, podemos revisar rápidamente su tamaño, sus primeras filas y los nombres de algunas variables:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(enif_tmodulo)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 13554   382</code></pre>
</div>
<div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">enif_tmodulo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb5-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(FOLIO, VIV_SEL, HOGAR, N_REN, REGION, SEXO, EDAD, FAC_ELE) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>()</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 6 × 8
  FOLIO VIV_SEL HOGAR N_REN REGION  SEXO  EDAD FAC_ELE
  &lt;chr&gt; &lt;chr&gt;   &lt;dbl&gt; &lt;chr&gt;  &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;   &lt;dbl&gt;
1 00001 01          1 01         3     2    83    3807
2 00002 02          1 01         3     2    33    1903
3 00003 03          1 04         3     1    30    8897
4 00004 04          1 01         3     2    64    5710
5 00005 05          1 01         3     1    70   14236
6 00006 01          1 04         3     2    20    5264</code></pre>
</div>
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(enif_tmodulo)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>]</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [1] "FOLIO"   "VIV_SEL" "HOGAR"   "N_REN"   "P3_1_1"  "P3_1_2"  "P3_2"   
 [8] "P3_3"    "P3_4"    "P3_5"    "P3_6"    "P3_7"    "P3_8A"   "P3_8B"  
[15] "P3_9"    "P3_10"   "P3_11"   "P4_1"    "P4_2_1"  "P4_2_2"  "P4_2_3" 
[22] "P4_2_4"  "P4_2_5"  "P4_3"    "P4_4_1"  "P4_4_2"  "P4_4_3"  "P4_4_4" 
[29] "P4_4_5"  "P4_4_6" </code></pre>
</div>
</div>
<p>Las salidas nos confirman que el archivo fue importado correctamente. También nos permiten observar que la ENIF no es una base pequeña, pero tampoco es inmanejable. En esta tabla cada fila corresponde a una persona entrevistada y las columnas contienen tanto sus respuestas como variables necesarias para expandir correctamente los resultados a la población total. Para este primer ejemplo nos interesa construir una variable sencilla: si la persona tiene al menos una cuenta o producto financiero de los enlistados en las preguntas <code>P5_4_1</code> a <code>P5_4_9</code>.</p>
<p>Estas variables preguntan, por ejemplo, si la persona tiene cuenta o tarjeta de nómina, cuenta de pensión, cuenta para recibir apoyos de gobierno, cuenta de ahorro, cuenta de cheques, depósito a plazo fijo, fondo de inversión, cuenta contratada por internet o alguna otra cuenta. Como todas usan el código <code>1</code> para “Sí” y <code>2</code> para “No”, podemos crear una variable indicadora que valga <code>1</code> si la persona respondió “Sí” en al menos una de ellas y <code>0</code> en caso contrario.</p>
<p>Además, en el mismo bloque recodificaremos dos variables que usaremos para describir los resultados: <code>REGION</code> y <code>SEXO</code>. En la base original estas variables vienen como códigos numéricos; por ejemplo, <code>SEXO</code> usa <code>1</code> para hombres y <code>2</code> para mujeres. Para que las tablas y gráficas sean más fáciles de leer, las convertiremos a variables categóricas con etiquetas:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">enif_tmodulo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> enif_tmodulo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb9-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb9-3">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tiene_cuenta =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(</span>
<span id="cb9-4">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_any</span>(</span>
<span id="cb9-5">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">starts_with</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"P5_4_"</span>),</span>
<span id="cb9-6">        <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coalesce</span>(.x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb9-7">      )</span>
<span id="cb9-8">    ),</span>
<span id="cb9-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">region =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(</span>
<span id="cb9-10">      REGION,</span>
<span id="cb9-11">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>,</span>
<span id="cb9-12">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(</span>
<span id="cb9-13">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Noroeste"</span>,</span>
<span id="cb9-14">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Noreste"</span>,</span>
<span id="cb9-15">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Occidente y Bajío"</span>,</span>
<span id="cb9-16">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Ciudad de México"</span>,</span>
<span id="cb9-17">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Centro Sur y Oriente"</span>,</span>
<span id="cb9-18">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sur"</span></span>
<span id="cb9-19">      )</span>
<span id="cb9-20">    ),</span>
<span id="cb9-21">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sexo =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(</span>
<span id="cb9-22">      SEXO,</span>
<span id="cb9-23">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb9-24">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hombre"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mujer"</span>)</span>
<span id="cb9-25">    )</span>
<span id="cb9-26">  )</span></code></pre></div>
</div>
<p>Después de crear <code>tiene_cuenta</code> y de recodificar variables de región y de sexo, podemos revisar algunas filas y columnas para comprobar que los cambios fueron aplicados como esperamos.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">enif_tmodulo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb10-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(region, sexo, P5_4_1, P5_4_2, P5_4_3, tiene_cuenta) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb10-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 8 × 6
  region            sexo   P5_4_1 P5_4_2 P5_4_3 tiene_cuenta
  &lt;fct&gt;             &lt;fct&gt;   &lt;dbl&gt;  &lt;dbl&gt;  &lt;dbl&gt;        &lt;dbl&gt;
1 Occidente y Bajío Mujer       2      2      1            1
2 Occidente y Bajío Mujer       2      2      1            1
3 Occidente y Bajío Hombre      2      2      2            0
4 Occidente y Bajío Mujer       2      2      2            0
5 Occidente y Bajío Hombre      2      2      1            1
6 Occidente y Bajío Mujer       1      2      2            1
7 Occidente y Bajío Mujer       2      1      2            1
8 Occidente y Bajío Hombre      2      2      2            0</code></pre>
</div>
</div>
<p>La variable <code>tiene_cuenta</code> queda codificada como una variable binaria: <code>1</code> si la persona tiene al menos una cuenta y <code>0</code> si no. Esto es útil porque el promedio de una variable binaria puede interpretarse como una proporción. Por ejemplo, si el promedio ponderado de <code>tiene_cuenta</code> fuera <code>0.55</code>, eso significaría que aproximadamente 55% de la población tiene al menos una cuenta.</p>
<section id="diseño-muestral-pesos-estratos-y-unidades-primarias" class="level3">
<h3 class="anchored" data-anchor-id="diseño-muestral-pesos-estratos-y-unidades-primarias">Diseño muestral: pesos, estratos y unidades primarias</h3>
<p>Antes de calcular cualquier porcentaje, hay un punto metodológico importante. Las encuestas nacionales como la ENIF no suelen ser muestras aleatorias simples. De acuerdo con el <a href="https://www.inegi.org.mx/contenidos/productos/prod_serv/contenidos/espanol/bvinegi/productos/nueva_estruc/889463903888.pdf">diseño muestral de la ENIF 2021</a>, la muestra fue probabilística, trietápica, estratificada y por conglomerados, donde la unidad última de selección fueron las personas de 18 años y más. En términos prácticos, esto significa que primero se seleccionan unidades primarias de muestreo, después viviendas y finalmente una persona adulta dentro de la vivienda seleccionada. Por eso no basta con calcular promedios simples usando <code>mean()</code>.</p>
<p>En la ENIF, tres variables son centrales para respetar ese diseño:</p>
<ul>
<li><code>FAC_ELE</code>: factor de expansión para la población de 18 años y más.</li>
<li><code>UPM_DIS</code>: unidad primaria de muestreo.</li>
<li><code>EST_DIS</code>: estrato de diseño.</li>
</ul>
<p>El <strong>factor de expansión</strong> indica cuántas personas de la población representa cada persona entrevistada. La intuición básica de un peso muestral parte de la probabilidad de inclusión: si <img src="https://latex.codecogs.com/png.latex?%5Cpi_i"> es la probabilidad de inclusión de la persona <img src="https://latex.codecogs.com/png.latex?i"> en la muestra, un peso base puede escribirse como:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Aw_i%20=%20%5Cfrac%7B1%7D%7B%5Cpi_i%7D%0A"></p>
<p>Así, una persona con peso <img src="https://latex.codecogs.com/png.latex?w_i%20=%20800"> representa aproximadamente a 800 personas con características similares en la población. En la práctica, el factor final publicado por INEGI no se queda necesariamente en ese peso base: también puede incorporar ajustes por no respuesta y por proyección poblacional. Aun así, para estimar una proporción poblacional, la idea operativa sigue siendo la misma: no usamos el promedio simple de una variable binaria, sino una media ponderada:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%7Bp%7D%20=%0A%5Cfrac%7B%5Csum_%7Bi%20%5Cin%20s%7D%20w_i%20y_i%7D%7B%5Csum_%7Bi%20%5Cin%20s%7D%20w_i%7D%0A"></p>
<p>donde <img src="https://latex.codecogs.com/png.latex?y_i"> vale <code>1</code> si la persona tiene la característica de interés y <code>0</code> si no la tiene. En nuestro caso, <img src="https://latex.codecogs.com/png.latex?y_i"> será la variable <code>tiene_cuenta</code>.</p>
<p>La <strong>unidad primaria de muestreo</strong> (<code>UPM_DIS</code>) identifica los conglomerados que fueron seleccionados en la primera etapa del muestreo. En la documentación de INEGI, las UPM son agrupaciones de viviendas formadas de manera distinta según el ámbito urbano o rural. Esto importa porque las personas dentro de una misma unidad primaria pueden parecerse más entre sí que personas seleccionadas en lugares distintos. Si ignoramos esa dependencia, los errores estándar pueden quedar mal estimados.</p>
<p>El <strong>estrato de diseño</strong> (<code>EST_DIS</code>) identifica grupos dentro de los cuales se seleccionaron unidades bajo condiciones similares. Incluir los estratos permite que R calcule la varianza de los estimadores de acuerdo con el diseño usado en la encuesta. En términos prácticos, los pesos entran tanto en las estimaciones puntuales como en el cálculo de la varianza; las unidades primarias y los estratos, por su parte, son indispensables para que los errores estándar, los intervalos de confianza y las pruebas estadísticas reflejen la estructura real del muestreo.</p>
<p>Esta es la lógica general detrás del análisis de encuestas complejas con software especializado, como documenta Thomas Lumley en el paquete <a href="https://r-survey.r-forge.r-project.org/survey/example-design.html"><code>{survey}</code></a> y en su <a href="https://econpapers.repec.org/article/jssjstsof/v_3a009_3ai08.htm">artículo sobre el análisis de muestras complejas en R</a>.</p>
<div class="callout callout-style-default callout-tip callout-titled" title="Idea clave">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Idea clave
</div>
</div>
<div class="callout-body-container callout-body">
<p>Si usamos <code>mean(tiene_cuenta)</code>, tratamos a la ENIF como si fuera una muestra aleatoria simple y como si todas las personas entrevistadas representaran lo mismo. Si usamos el diseño muestral con <code>FAC_ELE</code>, <code>UPM_DIS</code> y <code>EST_DIS</code>, tratamos a la encuesta como lo que realmente es: una muestra compleja diseñada para representar a la población.</p>
</div>
</div>
</section>
<section id="estimaciones-con-el-paquete-survey" class="level3">
<h3 class="anchored" data-anchor-id="estimaciones-con-el-paquete-survey">Estimaciones con el paquete survey</h3>
<p>Antes de realizar cualquier cálculo, configuraremos una opción preventiva de <code>{survey}</code> para indicar cómo tratar estratos que tienen una sola unidad primaria de muestreo. En este ejemplo puede no ser indispensable, pero es una regla útil cuando después hacemos estimaciones para subgrupos o cortes específicos, donde sí podrían aparecer estratos con una sola UPM. La opción quedará activa durante toda la sesión de trabajo en R:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">options</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">survey.lonely.psu =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"adjust"</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># regla preventiva para estratos con una sola UPM</span></span></code></pre></div>
</div>
<p>Con <code>{survey}</code>, necesitamos crear un objeto de diseño muestral para comenzar a trabajar. Este objeto le dice a R cuáles son los pesos, las unidades primarias y los estratos que debe usar en las estimaciones. Aunque el diseño completo de la ENIF es trietápico, en este tutorial declaramos la UPM de diseño que INEGI publica en los microdatos, que es una aproximación común cuando se analizan microdatos oficiales con variables de diseño:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">diseno_enif <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">svydesign</span>(</span>
<span id="cb13-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ids =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>UPM_DIS,</span>
<span id="cb13-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strata =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>EST_DIS,</span>
<span id="cb13-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weights =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>FAC_ELE,</span>
<span id="cb13-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> enif_tmodulo,</span>
<span id="cb13-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nest =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span></span>
<span id="cb13-7">)</span></code></pre></div>
</div>
<p>El argumento <code>nest = TRUE</code> es útil cuando los identificadores de las unidades primarias pueden repetirse entre estratos. Con esto, R interpreta las unidades primarias como anidadas dentro de cada estrato. Asimismo, vale la pena notar el uso del símbolo <code>~</code> antes de <code>UPM_DIS</code>, <code>EST_DIS</code> y <code>FAC_ELE</code>. En este caso, <code>~</code> no significa “aproximadamente”; es la sintaxis de fórmulas de R. Si, por ejemplo, escribiéramos <code>weights = FAC_ELE</code>, R intentaría encontrar un objeto llamado <code>FAC_ELE</code> fuera de la base de datos y el código fallaría. En cambio, al escribir <code>weights = ~FAC_ELE</code>, le indicamos a <code>{survey}</code> que debe buscar esa variable dentro de <code>data = enif_tmodulo</code>. Lo mismo ocurre con <code>ids = ~UPM_DIS</code> y <code>strata = ~EST_DIS</code>.</p>
<p>Ahora podemos estimar el porcentaje nacional de personas con al menos una cuenta:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">svymean</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>tiene_cuenta, diseno_enif, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>                mean     SE
tiene_cuenta 0.50339 0.0073</code></pre>
</div>
</div>
<p>El resultado nos devuelve la proporción estimada y, de manera predeterminada, su error estándar. En este caso, la estimación nacional es cercana a 50.3%, con un error estándar de 0.73%. También podemos calcular la misma estimación por región con <code>svyby()</code>:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">cuentas_region_survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">svyby</span>(</span>
<span id="cb16-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">formula =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>tiene_cuenta,</span>
<span id="cb16-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>region,</span>
<span id="cb16-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> diseno_enif,</span>
<span id="cb16-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">FUN =</span> svymean,</span>
<span id="cb16-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>,</span>
<span id="cb16-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vartype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"se"</span></span>
<span id="cb16-8">) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb16-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.data.frame</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb16-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb16-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">porcentaje =</span> tiene_cuenta <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,</span>
<span id="cb16-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error_estandar =</span> se <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb16-13">  )</span>
<span id="cb16-14"></span>
<span id="cb16-15">cuentas_region_survey</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>                                   region tiene_cuenta         se porcentaje
Noroeste                         Noroeste    0.5839476 0.01424968   58.39476
Noreste                           Noreste    0.5764684 0.01181391   57.64684
Occidente y Bajío       Occidente y Bajío    0.5059088 0.01838211   50.59088
Ciudad de México         Ciudad de México    0.6156021 0.01993839   61.56021
Centro Sur y Oriente Centro Sur y Oriente    0.4421749 0.01605186   44.21749
Sur                                   Sur    0.4390515 0.01654713   43.90515
                     error_estandar
Noroeste                   1.424968
Noreste                    1.181391
Occidente y Bajío          1.838211
Ciudad de México           1.993839
Centro Sur y Oriente       1.605186
Sur                        1.654713</code></pre>
</div>
</div>
<p>La salida de <code>svyby()</code> nos devuelve una fila por región. La columna <code>tiene_cuenta</code> contiene la proporción estimada, <code>se</code> contiene el error estándar y las dos últimas columnas expresan esos mismos valores en porcentaje.</p>
<p>Este resultado ya es una tabla mucho más útil: contiene una estimación por región y, además, el error estándar correspondiente. Esa diferencia es importante porque no solo queremos saber cuál es el porcentaje estimado, sino también qué tan precisa es esa estimación.</p>
</section>
<section id="la-misma-estimación-con-srvyr" class="level3">
<h3 class="anchored" data-anchor-id="la-misma-estimación-con-srvyr">La misma estimación con srvyr</h3>
<p>Ahora hagamos el mismo cálculo usando <code>{srvyr}</code>. La ventaja es que la sintaxis se parece más al flujo normal de <code>{dplyr}</code>. Primero declararemos el diseño, luego agruparemos y resumiremos.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">diseno_enif_srvyr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> enif_tmodulo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb18-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as_survey_design</span>(</span>
<span id="cb18-3">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ids =</span> UPM_DIS,</span>
<span id="cb18-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strata =</span> EST_DIS,</span>
<span id="cb18-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weights =</span> FAC_ELE,</span>
<span id="cb18-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nest =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span></span>
<span id="cb18-7">  )</span></code></pre></div>
</div>
<p>Una vez creado el diseño, podemos estimar el porcentaje por región con <code>group_by()</code> y <code>summarize()</code>:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1">cuentas_region <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> diseno_enif_srvyr <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb19-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(region) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb19-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarize</span>(</span>
<span id="cb19-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prop_cuenta =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">survey_mean</span>(</span>
<span id="cb19-5">      tiene_cuenta,</span>
<span id="cb19-6">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vartype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"se"</span>,</span>
<span id="cb19-7">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span></span>
<span id="cb19-8">    )</span>
<span id="cb19-9">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb19-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb19-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">porcentaje =</span> prop_cuenta <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,</span>
<span id="cb19-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error_estandar =</span> prop_cuenta_se <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb19-13">  )</span>
<span id="cb19-14"></span>
<span id="cb19-15">cuentas_region</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 6 × 5
  region               prop_cuenta prop_cuenta_se porcentaje error_estandar
  &lt;fct&gt;                      &lt;dbl&gt;          &lt;dbl&gt;      &lt;dbl&gt;          &lt;dbl&gt;
1 Noroeste                   0.584         0.0142       58.4           1.42
2 Noreste                    0.576         0.0118       57.6           1.18
3 Occidente y Bajío          0.506         0.0184       50.6           1.84
4 Ciudad de México           0.616         0.0199       61.6           1.99
5 Centro Sur y Oriente       0.442         0.0161       44.2           1.61
6 Sur                        0.439         0.0165       43.9           1.65</code></pre>
</div>
</div>
<p>La salida de <code>{srvyr}</code>, como podemos observar, es más compacta y conserva el formato de tibble.</p>
<p>El resultado es equivalente al que obtuvimos con <code>{survey}</code>, pero escrito de una forma más cercana a la que solemos usar para manipular datos con <code>{dplyr}</code>. Para construir una visualización un poco más informativa, ahora repetiremos la estimación separando por región y sexo. Además del porcentaje estimado, le pediremos a <code>{srvyr}</code> que calcule intervalos de confianza de 95%, en lugar del error estándar:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">cuentas_region_sexo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> diseno_enif_srvyr <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb21-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(region, sexo) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb21-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarize</span>(</span>
<span id="cb21-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prop_cuenta =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">survey_mean</span>(</span>
<span id="cb21-5">      tiene_cuenta,</span>
<span id="cb21-6">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vartype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ci"</span>,</span>
<span id="cb21-7">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">level =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>,</span>
<span id="cb21-8">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span></span>
<span id="cb21-9">    )</span>
<span id="cb21-10">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb21-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb21-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">porcentaje =</span> prop_cuenta <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,</span>
<span id="cb21-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">intervalo_inf =</span> prop_cuenta_low <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,</span>
<span id="cb21-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">intervalo_sup =</span> prop_cuenta_upp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb21-15">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb21-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ungroup</span>()</span>
<span id="cb21-17"></span>
<span id="cb21-18">cuentas_region_sexo</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 12 × 8
   region           sexo  prop_cuenta prop_cuenta_low prop_cuenta_upp porcentaje
   &lt;fct&gt;            &lt;fct&gt;       &lt;dbl&gt;           &lt;dbl&gt;           &lt;dbl&gt;      &lt;dbl&gt;
 1 Noroeste         Homb…       0.646           0.605           0.687       64.6
 2 Noroeste         Mujer       0.525           0.492           0.558       52.5
 3 Noreste          Homb…       0.647           0.612           0.683       64.7
 4 Noreste          Mujer       0.509           0.478           0.541       50.9
 5 Occidente y Baj… Homb…       0.579           0.527           0.631       57.9
 6 Occidente y Baj… Mujer       0.438           0.400           0.476       43.8
 7 Ciudad de México Homb…       0.631           0.572           0.689       63.1
 8 Ciudad de México Mujer       0.603           0.551           0.655       60.3
 9 Centro Sur y Or… Homb…       0.545           0.502           0.588       54.5
10 Centro Sur y Or… Mujer       0.354           0.317           0.390       35.4
11 Sur              Homb…       0.468           0.430           0.506       46.8
12 Sur              Mujer       0.414           0.375           0.453       41.4
# ℹ 2 more variables: intervalo_inf &lt;dbl&gt;, intervalo_sup &lt;dbl&gt;</code></pre>
</div>
</div>
<p>Con esta tabla ya podemos construir una gráfica de barras por región y sexo. Para facilitar la lectura, ordenaremos las regiones de acuerdo con el subgrupo que tenga el mayor porcentaje estimado dentro de cada región. Las etiquetas al final de cada barra muestran el porcentaje estimado, mientras que las barras de error muestran el intervalo de confianza de 95%:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1">posicion_barras <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>)</span>
<span id="cb23-2"></span>
<span id="cb23-3">limite_grafica_enif <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(cuentas_region_sexo<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intervalo_sup, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span></span>
<span id="cb23-4"></span>
<span id="cb23-5">orden_regiones <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cuentas_region_sexo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb23-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(region) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb23-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarize</span>(</span>
<span id="cb23-8">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max_porcentaje =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(porcentaje, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>),</span>
<span id="cb23-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.groups =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drop"</span></span>
<span id="cb23-10">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb23-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">arrange</span>(max_porcentaje) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb23-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pull</span>(region)</span>
<span id="cb23-13"></span>
<span id="cb23-14">cuentas_region_sexo_ordenado <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cuentas_region_sexo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb23-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb23-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">region_ordenada =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(region, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> orden_regiones)</span>
<span id="cb23-17">  )</span>
<span id="cb23-18"></span>
<span id="cb23-19">caption_enif <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(</span>
<span id="cb23-20">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fuente: Elaboración propia con datos de la ENIF 2021, INEGI."</span>,</span>
<span id="cb23-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(</span>
<span id="cb23-22">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">strwrap</span>(</span>
<span id="cb23-23">      <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nota: Se considera que una persona tiene cuenta si reporta al menos una cuenta o tarjeta de nómina, pensión, apoyos de gobierno, ahorro, cheques, depósito a plazo fijo, fondo de inversión, cuenta digital u otro producto similar (P5_4_1 a P5_4_9)."</span>,</span>
<span id="cb23-24">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">95</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">collapse =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sep =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb23-25"></span>
<span id="cb23-26">grafica_enif <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(</span>
<span id="cb23-27">  cuentas_region_sexo_ordenado,</span>
<span id="cb23-28">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> region_ordenada, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> porcentaje, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> sexo)</span>
<span id="cb23-29">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-30">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_col</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> posicion_barras, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.68</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(</span>
<span id="cb23-32">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> intervalo_inf, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> intervalo_sup),</span>
<span id="cb23-33">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> posicion_barras,</span>
<span id="cb23-34">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>,</span>
<span id="cb23-35">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb23-36">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-37">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_text</span>(</span>
<span id="cb23-38">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(</span>
<span id="cb23-39">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> intervalo_sup <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>,</span>
<span id="cb23-40">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">label_number</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">accuracy =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">suffix =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%"</span>)(porcentaje)</span>
<span id="cb23-41">    ),</span>
<span id="cb23-42">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> posicion_barras,</span>
<span id="cb23-43">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb23-44">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb23-45">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-46">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_flip</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-47">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_continuous</span>(</span>
<span id="cb23-48">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">label_number</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">suffix =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%"</span>),</span>
<span id="cb23-49">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, limite_grafica_enif),</span>
<span id="cb23-50">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>)</span>
<span id="cb23-51">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-52">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(</span>
<span id="cb23-53">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(</span>
<span id="cb23-54">      <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hombre"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#1A6F7A"</span>,</span>
<span id="cb23-55">      <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mujer"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#D96C4A"</span></span>
<span id="cb23-56">    ),</span>
<span id="cb23-57">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mujer"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hombre"</span>)</span>
<span id="cb23-58">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-59">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb23-60">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Personas con al menos una cuenta en una institución financiera</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">por región y por sexo"</span>,</span>
<span id="cb23-61">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ENIF 2021"</span>,</span>
<span id="cb23-62">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb23-63">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Porcentaje estimado"</span>,</span>
<span id="cb23-64">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb23-65">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> caption_enif</span>
<span id="cb23-66">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-67">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-68">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb23-69">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb23-70">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plot"</span>,</span>
<span id="cb23-71">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lineheight =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>),</span>
<span id="cb23-72">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plot"</span>,</span>
<span id="cb23-73">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text.y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">margin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">margin</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)),</span>
<span id="cb23-74">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.title.x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>),</span>
<span id="cb23-75">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.ticks.y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb23-76">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major.y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb23-77">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span></span>
<span id="cb23-78">  )</span>
<span id="cb23-79"></span>
<span id="cb23-80">grafica_enif</span></code></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/unnamed-chunk-13-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2"><img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/index_files/figure-html/unnamed-chunk-13-1.png" class="img-fluid figure-img" width="672"></a></p>
</figure>
</div>
</div>
</div>
<p>La lectura de la gráfica anterior es directa: las barras más largas indican un mayor porcentaje estimado de personas con al menos una cuenta. Al separar por sexo, también podemos observar diferencias dentro de cada región. Lo importante es que esta gráfica no se construyó con conteos simples de la muestra, sino con estimaciones ponderadas que toman en cuenta el diseño muestral de la ENIF y que además muestran la incertidumbre de cada estimación mediante barras de error.</p>
</section>
</section>
<section id="análisis-de-la-enafin" class="level2">
<h2 class="anchored" data-anchor-id="análisis-de-la-enafin">Análisis de la ENAFIN</h2>
<p>Pasemos ahora a la ENAFIN 2021. Aquí conviene hacer una distinción importante: el archivo de datos abiertos de esta encuesta no está organizado igual que el de la ENIF. Mientras que en la ENIF trabajamos con microdatos de personas entrevistadas, en la ENAFIN el archivo disponible contiene información ya agregada por dominios de estudio: tamaño de empresa, sector de actividad y tamaño de localidad.</p>
<p>De igual manera, es importante tener claro el universo al que se refiere esta encuesta. La ENAFIN 2021 no representa a todas las empresas del país, sino a empresas con seis o más personas ocupadas en los sectores de construcción, manufacturas, comercio y servicios privados no financieros, ubicadas en localidades de 50,000 habitantes o más. Por lo tanto, las conclusiones de esta sección deben leerse dentro de ese universo específico.</p>
<p>En esta parte no vamos a crear un objeto de diseño muestral con <code>{survey}</code> o <code>{srvyr}</code>. No porque los pesos no importen, sino porque el archivo que estamos usando ya contiene estimaciones agregadas. En este caso, nuestro trabajo consiste más bien en seleccionar las columnas relevantes, calcular porcentajes a partir de los totales disponibles y visualizar los resultados.</p>
<p>Leemos primero el archivo CSV de la ENAFIN:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1">ruta_enafin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(</span>
<span id="cb24-2">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enafin_2019_2021_csv/"</span>,</span>
<span id="cb24-3">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"conjunto_de_datos/"</span>,</span>
<span id="cb24-4">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enafin_2019_2021.csv"</span></span>
<span id="cb24-5">)</span>
<span id="cb24-6"></span>
<span id="cb24-7">enafin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_csv</span>(</span>
<span id="cb24-8">  ruta_enafin,</span>
<span id="cb24-9">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"NA"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"*"</span>),</span>
<span id="cb24-10">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">show_col_types =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb24-11">)</span>
<span id="cb24-12"></span>
<span id="cb24-13">enafin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb24-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(DOMINIO_ESTUDIO, C_1, D_8, Q_8, AD_8)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 11 × 5
   DOMINIO_ESTUDIO                              C_1    D_8    Q_8   AD_8
   &lt;chr&gt;                                      &lt;dbl&gt;  &lt;dbl&gt;  &lt;dbl&gt;  &lt;dbl&gt;
 1 total                                    280489. 93562. 88306. 98621.
 2 grande                                    14219.  2057.  4382.  7779.
 3 mediana                                   19329.  3855.  7404.  8070.
 4 pequeña                                   98917. 32036. 34582. 32298.
 5 micro                                    148024. 55613. 41937. 50473.
 6 construcción                              11652.  3806.  3959.  3887.
 7 manufacturas                              44708. 14564. 14199. 15946.
 8 comercio                                  76181. 21180. 24995. 30006.
 9 servicios                                147948. 54012. 45154. 48782.
10 Localidad de 500,000 y más habitantes    156861. 52427. 47028. 57406.
11 Localidad de 50,000 a 499,999 habitantes 123628. 41135. 41278. 41215.</code></pre>
</div>
</div>
<p>Aquí usamos <code>na = c("", "NA", "*")</code> porque en este archivo algunos valores no disponibles aparecen marcados con asterisco (<code>*</code>). Al indicarle eso a R desde la lectura, evitamos que columnas numéricas se interpreten como texto. Como salida, R nos muestra una tabla con el dominio de estudio y las variables que usaremos más adelante. Esta vista seleccionada evita imprimir todas las columnas del archivo, lo cual sería poco práctico para este tutorial.</p>
<p>En el siguiente ejemplo analizaremos qué tanto afectó la falta de financiamiento a la operación de las empresas, comparando por el tamaño de las mismas. De acuerdo con el diccionario de datos, usaremos estas variables:</p>
<ul>
<li><code>C_1</code>: total de empresas en el dominio de estudio.</li>
<li><code>D_8</code>: número de empresas a las que la falta de financiamiento afectó mucho.</li>
<li><code>Q_8</code>: número de empresas a las que la falta de financiamiento afectó poco.</li>
<li><code>AD_8</code>: número de empresas a las que la falta de financiamiento no afectó.</li>
</ul>
<p>Primero filtramos los dominios de tamaño de empresa y transformamos los conteos en porcentajes:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1">afectacion_financiamiento <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> enafin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb26-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(DOMINIO_ESTUDIO <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"micro"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pequeña"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mediana"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grande"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb26-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">transmute</span>(</span>
<span id="cb26-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tamano =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(</span>
<span id="cb26-5">      DOMINIO_ESTUDIO,</span>
<span id="cb26-6">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"micro"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pequeña"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mediana"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grande"</span>),</span>
<span id="cb26-7">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Micro"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pequeña"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mediana"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Grande"</span>)</span>
<span id="cb26-8">    ),</span>
<span id="cb26-9">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectó mucho"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> D_8 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> C_1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,</span>
<span id="cb26-10">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectó poco"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> Q_8 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> C_1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,</span>
<span id="cb26-11">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"No afectó"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> AD_8 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> C_1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb26-12">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb26-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pivot_longer</span>(</span>
<span id="cb26-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cols =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>tamano,</span>
<span id="cb26-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names_to =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"respuesta"</span>,</span>
<span id="cb26-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values_to =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"porcentaje"</span></span>
<span id="cb26-17">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb26-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb26-19">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">respuesta =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(</span>
<span id="cb26-20">      respuesta,</span>
<span id="cb26-21">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectó mucho"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectó poco"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"No afectó"</span>)</span>
<span id="cb26-22">    )</span>
<span id="cb26-23">  )</span>
<span id="cb26-24"></span>
<span id="cb26-25">afectacion_financiamiento</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 12 × 3
   tamano  respuesta    porcentaje
   &lt;fct&gt;   &lt;fct&gt;             &lt;dbl&gt;
 1 Grande  Afectó mucho       14.5
 2 Grande  Afectó poco        30.8
 3 Grande  No afectó          54.7
 4 Mediana Afectó mucho       19.9
 5 Mediana Afectó poco        38.3
 6 Mediana No afectó          41.8
 7 Pequeña Afectó mucho       32.4
 8 Pequeña Afectó poco        35.0
 9 Pequeña No afectó          32.7
10 Micro   Afectó mucho       37.6
11 Micro   Afectó poco        28.3
12 Micro   No afectó          34.1</code></pre>
</div>
</div>
<p>El resultado queda en formato largo: una fila por combinación de tamaño de empresa y respuesta. Ahora podemos construir una gráfica de barras apiladas para comparar la distribución de respuestas por tamaño de empresa:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1">grafica_enafin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(</span>
<span id="cb28-2">  afectacion_financiamiento,</span>
<span id="cb28-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tamano, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> porcentaje, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> respuesta)</span>
<span id="cb28-4">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_col</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_text</span>(</span>
<span id="cb28-7">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(</span>
<span id="cb28-8">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">label_number</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">accuracy =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">suffix =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%"</span>)(porcentaje)</span>
<span id="cb28-9">    ),</span>
<span id="cb28-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_stack</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vjust =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>),</span>
<span id="cb28-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>,</span>
<span id="cb28-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fontface =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>,</span>
<span id="cb28-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb28-14">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_continuous</span>(</span>
<span id="cb28-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">label_number</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">suffix =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%"</span>),</span>
<span id="cb28-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb28-18">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(</span>
<span id="cb28-20">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(</span>
<span id="cb28-21">      <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectó mucho"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#9B2226"</span>,</span>
<span id="cb28-22">      <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectó poco"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#EE9B00"</span>,</span>
<span id="cb28-23">      <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"No afectó"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#0A9396"</span></span>
<span id="cb28-24">    )</span>
<span id="cb28-25">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb28-27">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Afectación por falta de financiamiento según tamaño de empresa"</span>,</span>
<span id="cb28-28">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ENAFIN 2021"</span>,</span>
<span id="cb28-29">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Tamaño de empresa"</span>,</span>
<span id="cb28-30">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Porcentaje de empresas"</span>,</span>
<span id="cb28-31">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb28-32">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fuente: Elaboración propia con datos de la ENAFIN 2021, INEGI.</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Nota: Universo de empresas con seis o más personas ocupadas en localidades de 50,000 habitantes o más."</span></span>
<span id="cb28-33">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-34">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-35">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb28-36">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb28-37">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plot"</span>,</span>
<span id="cb28-38">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>),</span>
<span id="cb28-39">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plot"</span>,</span>
<span id="cb28-40">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span></span>
<span id="cb28-41">  )</span>
<span id="cb28-42"></span>
<span id="cb28-43">grafica_enafin</span></code></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/unnamed-chunk-16-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3"><img src="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/index_files/figure-html/unnamed-chunk-16-1.png" class="img-fluid figure-img" width="672"></a></p>
</figure>
</div>
</div>
</div>
<p>La gráfica anterior ofrece una comparación descriptiva de las respuestas según el tamaño de la empresa. En particular, dentro del universo de la ENAFIN, las empresas micro y pequeñas muestran una proporción mayor en la categoría “Afectó mucho”, mientras que las empresas grandes concentran una mayor proporción en “No afectó”. Esta lectura es útil como primera exploración, pero no debe interpretarse como una prueba formal de diferencias entre grupos, ya que aquí estamos trabajando con tabulados agregados y no con intervalos de confianza o errores estándar para estas estimaciones.</p>
</section>
</section>
<section id="guardar-las-gráficas" class="level1">
<h1>Guardar las gráficas</h1>
<p>Finalmente, si queremos guardar las gráficas que construimos con <code>{ggplot2}</code>, podemos usar <code>ggsave()</code>. Por ejemplo, para guardar la gráfica de la ENIF:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggsave</span>(</span>
<span id="cb29-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">filename =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enif_cuentas_region.png"</span>,</span>
<span id="cb29-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot =</span> grafica_enif,</span>
<span id="cb29-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>,</span>
<span id="cb29-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,</span>
<span id="cb29-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dpi =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>,</span>
<span id="cb29-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bg =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span></span>
<span id="cb29-8">)</span></code></pre></div>
</div>
<p>Y para guardar la gráfica de la ENAFIN:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggsave</span>(</span>
<span id="cb30-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">filename =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enafin_financiamiento_tamano.png"</span>,</span>
<span id="cb30-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot =</span> grafica_enafin,</span>
<span id="cb30-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>,</span>
<span id="cb30-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,</span>
<span id="cb30-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dpi =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>,</span>
<span id="cb30-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bg =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span></span>
<span id="cb30-8">)</span></code></pre></div>
</div>
<p>En ambos casos, <code>width</code> y <code>height</code> controlan el tamaño de la imagen, mientras que <code>dpi</code> controla la resolución. Un valor de 300 suele ser suficiente para una imagen de buena calidad en pantalla y en documentos.</p>
</section>
<section id="conclusión" class="level1">
<h1>Conclusión</h1>
<p>En este tutorial vimos cómo descargar, leer y analizar información de la ENIF y la ENAFIN usando R. Con la ENIF trabajamos con microdatos, por lo que fue necesario declarar el diseño operativo con las variables públicas de diseño: pesos, estratos y unidades primarias de muestreo. También vimos dos formas de hacerlo: con <code>{survey}</code>, usando la sintaxis clásica, y con <code>{srvyr}</code>, usando una sintaxis más cercana a <code>{dplyr}</code>. Con la ENAFIN, en cambio, trabajamos con un archivo de datos agregados por dominios de estudio. Por eso el procesamiento fue distinto: únicamente seleccionamos las columnas en las que estabamos interesados, calculamos porcentajes y visualizamos diferencias por tamaño de empresa.</p>
<p>La idea central es que no todas las encuestas se procesan igual. Cuando tenemos microdatos con diseño muestral, debemos incorporar pesos, estratos y conglomerados para obtener estimaciones adecuadas. En ambos casos, R nos permite construir un flujo de trabajo claro: leer datos, entender su estructura, transformar variables y comunicar resultados mediante visualizaciones.</p>


</section>

 ]]></description>
  <category>R</category>
  <category>Tutorial</category>
  <category>Análisis de Datos</category>
  <category>Encuestas</category>
  <category>Visualización</category>
  <guid>https://alejandroromerog.github.io/blog/ENIF-ENAFIN/</guid>
  <pubDate>Tue, 02 Jun 2026 06:00:00 GMT</pubDate>
  <media:content url="https://alejandroromerog.github.io/blog/ENIF-ENAFIN/INEGI.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>R como SIG: Shapefiles, GeoPackages y mapas coropléticos de México</title>
  <link>https://alejandroromerog.github.io/blog/RComoSIG-Mapa/</link>
  <description><![CDATA[ 





<section id="introducción" class="level2">
<h2 class="anchored" data-anchor-id="introducción">Introducción</h2>
<p>Si nunca has trabajado con mapas en R, es completamente normal que términos como <em>SIG</em>, <em>Shapefile</em>, <em>GeoPackage</em>, <em>geometría</em> o <em>sistema de coordenadas</em> suenen un poco intimidantes. La buena noticia es que, una vez comprendamos las ideas básicas, gran parte del trabajo se parece bastante a lo que ya hacemos normalmente en R: leer archivos, limpiar datos, unir tablas y hacer visualizaciones.</p>
<p>Primero entenderemos qué es un SIG y qué tipo de datos utiliza. Después veremos dos de los formatos vectoriales más comunes: el <strong>Shapefile</strong> y el <strong>GeoPackage</strong>. Finalmente, construiremos <strong>mapas coropléticos</strong> de México por estado; es decir, mapas donde cada estado se colorea de acuerdo con el valor de una variable.</p>
<div class="callout callout-style-default callout-tip callout-titled" title="Nota">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Nota
</div>
</div>
<div class="callout-body-container callout-body">
<p>En los SIG existen dos grandes tipos de datos espaciales:</p>
<ul>
<li><strong>Vectoriales</strong>: Representan puntos, líneas y polígonos.</li>
<li><strong>Raster</strong>: Representan celdas o pixeles, como una imagen satelital o un modelo de elevación.</li>
</ul>
<p>En este tutorial trabajaremos con datos <strong>vectoriales</strong>, porque los estados de México pueden representarse como polígonos.</p>
</div>
</div>
</section>
<section id="qué-es-un-sig" class="level2">
<h2 class="anchored" data-anchor-id="qué-es-un-sig">¿Qué es un SIG?</h2>
<p>Un <strong>Sistema de Información Geográfica (SIG)</strong> es un conjunto de herramientas que permite almacenar, organizar, analizar y visualizar datos que tienen una ubicación en el espacio. En palabras más simples, un SIG nos ayuda a trabajar con datos que <em>viven</em> en un mapa. Por ejemplo, con un SIG podríamos responder (visualmente) a preguntas como estas:</p>
<ul>
<li>¿En qué estados hay mayor acceso a internet?</li>
<li>¿Qué municipios cuentan con mayor número de sucursales bancarias?</li>
<li>¿Cómo cambian ciertos indicadores entre regiones del país?</li>
</ul>
<p>Tradicionalmente, estas tareas se realizan con programas especializados como QGIS o ArcGIS. Sin embargo, R también puede funcionar como un SIG muy potente, especialmente cuando queremos combinar análisis estadístico, limpieza de datos y visualización dentro del mismo flujo de trabajo.</p>
</section>
<section id="r-como-sig" class="level2">
<h2 class="anchored" data-anchor-id="r-como-sig">R como SIG</h2>
<p>Cuando usamos R como SIG, normalmente trabajamos con objetos espaciales que guardan dos cosas al mismo tiempo:</p>
<ul>
<li>un conjunto de atributos, es decir, información como nombres, claves o indicadores y</li>
<li>una geometría, a saber, la forma y la ubicación espacial de cada observación.</li>
</ul>
<p>El paquete más importante para esto hoy en día es <code>{sf}</code>. Las siglas vienen de <strong>simple features</strong>, un estándar moderno para representar datos espaciales vectoriales. Una de sus ventajas es que un objeto <code>sf</code> se comporta de manera muy parecida a un <em>data frame</em>, así que muchas operaciones con <code>{dplyr}</code> funcionan de manera natural.</p>
</section>
<section id="shapefiles-y-geopackages" class="level2">
<h2 class="anchored" data-anchor-id="shapefiles-y-geopackages">Shapefiles y GeoPackages</h2>
<p>Antes de dibujar nuestro primer mapa, vale la pena entender los formatos en los que suelen venir los datos espaciales.</p>
<section id="shapefile" class="level3">
<h3 class="anchored" data-anchor-id="shapefile">Shapefile</h3>
<p>El <strong>Shapefile</strong> es el formato más conocido en la comunidad geoespacial. Fue desarrollado por <a href="https://www.esri.com/">ESRI</a> y durante muchos años ha sido el formato <em>clásico</em> para compartir y trabajar con capas vectoriales. Sin embargo, hay algo importante que suele confundir a quienes empiezan: un Shapefile no es realmente un solo archivo. En realidad, es un conjunto de archivos que trabajan juntos.</p>
<p>Los archivos más comunes son estos:</p>
<ul>
<li><code>.shp</code>: guarda la geometría;</li>
<li><code>.shx</code>: guarda un índice de la geometría;</li>
<li><code>.dbf</code>: guarda los atributos asociados en formato de tabla;</li>
<li><code>.prj</code>: guarda el sistema de coordenadas.</li>
</ul>
<p>En términos estrictos, para que un shapefile funcione correctamente y conserve tanto la geometría como los atributos, al menos deben estar presentes los archivos <code>.shp</code>, <code>.shx</code> y <code>.dbf</code>. Sin embargo, en la práctica también conviene que esté presente el archivo <code>.prj</code>, porque sin él perdemos la referencia espacial del objeto y después pueden surgir problemas al intentar superponer esa capa con otras.</p>
<p>Es decir, cuando alguien te comparte <em>un shapefile</em>, normalmente en realidad te está compartiendo varios archivos al mismo tiempo. Si falta alguno de los esenciales, es muy probable que la capa no pueda abrirse correctamente o que se abra con información incompleta.</p>
</section>
<section id="geopackage" class="level3">
<h3 class="anchored" data-anchor-id="geopackage">GeoPackage</h3>
<p>El <strong>GeoPackage</strong> o <strong>GPKG</strong> es un formato más moderno. Internamente está basado en <a href="https://sqlite.org/">SQLite</a> y fue diseñado como un estándar abierto para almacenar información geoespacial. Su principal ventaja es que todo queda guardado en <strong>un solo archivo</strong> con extensión <code>.gpkg</code>. Además, suele manejar mejor los nombres largos de variables, la codificación de texto y el almacenamiento de varias capas dentro del mismo archivo.</p>
</section>
<section id="cuál-conviene-usar" class="level3">
<h3 class="anchored" data-anchor-id="cuál-conviene-usar">¿Cuál conviene usar?</h3>
<p>Si necesitas máxima compatibilidad con software antiguo, el Shapefile sigue siendo útil. Empero, si estás empezando hoy y puedes elegir, el GeoPackage suele ser una mejor opción.</p>
</section>
</section>
<section id="preparación-del-entorno-de-trabajo" class="level2">
<h2 class="anchored" data-anchor-id="preparación-del-entorno-de-trabajo">Preparación del Entorno de trabajo</h2>
<p>Para este tutorial podríamos utilizar como fuente de información geoespacial directamente el <a href="https://www.inegi.org.mx/app/biblioteca/ficha.html?upc=794551163061">Marco Geoestadístico 2025 del INEGI</a>, que es la fuente oficial de referencia para la cartografía geoestadística de México. Sin embargo, para un primer acercamiento considero que esa descarga puede resultar algo pesada (<strong>245 MB</strong>), especialmente si nuestro objetivo inicial es simplemente aprender a leer una capa vectorial, entender su estructura y construir un mapa coroplético por entidad federativa. Por esa razón, en este tutorial utilizaremos una alternativa también oficial: la capa de <strong>División política estatal 1:250000. 2010</strong> de <a href="http://geoportal.conabio.gob.mx/metadatos/doc/html/dest_2010gw.html">CONABIO</a>. Esta capa es mucho más ligera y suficiente para fines didácticos como los nuestros: el recurso en formato <strong>Shapefile (coordenadas geográficas)</strong> tiene un tamaño de <strong>8.8 MB</strong> comprimido, lo cual la vuelve una opción mucho más manejable para aprender.</p>
<p>Ahora bien, nuestra variable de interés para el mapa coroplético será la <strong>pobreza</strong> por estado, definida de acuerdo con la <a href="https://www.coneval.org.mx/InformesPublicaciones/InformesPublicaciones/Documents/Metodologia-medicion-multidimensional-3er-edicion.pdf">tercera edición de la Metodología para la medición multidimensional de la pobreza</a> del extinto Consejo Nacional de Evaluación de la Política de Desarrollo Social (<a href="https://www.coneval.org.mx/Paginas/principal.aspx">CONEVAL</a>). El <a href="https://www.coneval.org.mx/Medicion/MP/paginas/ae_pobreza_2022.aspx">anexo estadístico 2016 - 2022</a> proporciona los datos de porcentaje de población en pobreza (moderada y extrema) por entidad federativa, que serán los que utilizaremos para nuestros mapas. Para obtener esta información, podemos ir a la página del anexo antes mencionado y simplemente darle clic al botón llamado <em>Anexo entidades federativas</em>, lo cual descargará un archivo <code>AE_estatal_2022.zip</code> que contiene un archivo Excel llamado <code>Anexo estad”stico entidades 2022.xlsx</code>.</p>
<p>Una vez que ya tenemos claro qué información utilizaremos y de dónde obtendremos tanto la cartografía como la variable de interés, el siguiente paso es preparar nuestro entorno de trabajo en R. Para este tutorial utilizaremos seis paquetes principales:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(sf) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para trabajar con datos espaciales</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(dplyr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para manipular datos en general</span></span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(tidyr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para transformar estructuras de datos</span></span>
<span id="cb1-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(stringi) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para manipular texto</span></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para crear gráficos</span></span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(readxl) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para leer nuestro archivo Excel</span></span></code></pre></div>
</div>
<p>El siguiente paso es importar los archivos que vamos a utilizar. Para simplificar el proceso, asumiré que tanto la carpeta que contiene el Shapefile extraída de <code>AE_estatal_2022.zip</code> llamada <code>dest_2010gw</code>, como el archivo de Excel se encuentran en la misma carpeta que el archivo <code>.R</code>, <code>.Rmd</code> o <code>.qmd</code> desde el cual estamos trabajando. Esta forma de organizar el proyecto es bastante útil cuando apenas estamos comenzando, porque nos permite leer los archivos directamente por su nombre, sin necesidad de escribir rutas más largas o complejas. Si quisiéramos organizar nuestro proyecto de una manera más estructurada, podríamos crear subcarpetas como <code>data</code> para guardar nuestros archivos de datos, y entonces la ruta para leer el Shapefile sería algo así como <code>data/dest_2010gw/dest_2010gw.shp</code>, y para el Excel sería <code>data/Anexo estadístico entidades 2022.xlsx</code>. Sin embargo, para este tutorial mantendremos las cosas simples y asumiremos que ambos archivos están en la raíz del proyecto.</p>
<p>Primero comenzaremos importando el Shapefile. Como ya se mencionó antes, aunque un Shapefile está compuesto por varios archivos, para leerlo en R basta con indicar la ruta del archivo <code>.shp</code>, siempre y cuando los demás componentes esenciales se encuentren en la misma carpeta. En nuestro caso, como la carpeta <code>dest_2010gw</code> está en la raíz del proyecto, podemos importarlo de la siguiente manera:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">mapa_mexico <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_read</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dest_2010gw/dest_2010gw.shp"</span>)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Reading layer `dest_2010gw' from data source 
  `/Users/ale_romero/Library/CloudStorage/OneDrive-CIDE/R/AlejandroRomeroG.github.io/blog/RComoSIG-Mapa/dest_2010gw/dest_2010gw.shp' 
  using driver `ESRI Shapefile'
Simple feature collection with 1212 features and 8 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -118.3665 ymin: 14.53496 xmax: -86.71074 ymax: 32.71873
Geodetic CRS:  WGS 84</code></pre>
</div>
</div>
<p>Si todo salió bien, R nos mostrará en la consola un breve resumen del objeto espacial que acabamos de importar: el número de observaciones (features), el número de variables (fields), el tipo de geometría, la extensión espacial del objeto y el sistema de referencia de coordenadas. En este caso, veremos que la capa se encuentra en el sistema <strong>WGS 84</strong>, uno de los más comunes para trabajar con información geográfica. Para inspeccionar con más detalle el objeto importado y sus atributos, basta con escribir su nombre:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">mapa_mexico</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>Simple feature collection with 1212 features and 8 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -118.3665 ymin: 14.53496 xmax: -86.71074 ymax: 32.71873
Geodetic CRS:  WGS 84
First 10 features:
           AREA    PERIMETER COV_ COV_ID         ENTIDAD    CAPITAL RASGO_GEOG
1  7.171369e+10 2273088.5899    2      1 BAJA CALIFORNIA   Mexicali       &lt;NA&gt;
2  4.778415e+05    3517.5845    3      2 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
3  4.242857e+04     916.2356    4      3 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
4  1.297501e+05    2259.5981    5      4 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
5  1.479776e+06    7917.4943    6      5 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
6  1.792021e+11 3759999.3858    7      6          SONORA Hermosillo       &lt;NA&gt;
7  1.341048e+08   70456.4252    8      7 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
8  1.617167e+07   18779.8250    9      8 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
9  2.469928e+11 3119522.9908   10      9       CHIHUAHUA  Chihuahua       &lt;NA&gt;
10 1.498113e+05    1522.8309   11     10 BAJA CALIFORNIA       &lt;NA&gt;       ISLA
   NUM_EDO                       geometry
1       02 POLYGON ((-117.0825 32.3816...
2       02 POLYGON ((-117.2944 32.4341...
3       02 POLYGON ((-117.2629 32.4233...
4       02 POLYGON ((-117.2595 32.4148...
5       02 POLYGON ((-117.2396 32.3907...
6       26 POLYGON ((-114.8133 32.4925...
7       02 POLYGON ((-114.7069 31.7452...
8       02 POLYGON ((-114.6085 31.7284...
9       08 POLYGON ((-108.7544 31.3346...
10      02 POLYGON ((-116.0428 30.7120...</code></pre>
</div>
</div>
<p>En este punto conviene detenernos un momento a observar qué acabamos de importar. Como puede verse, <code>mapa_mexico</code> no es un <em>data frame</em> cualquiera, sino un objeto de clase <code>sf</code>. Esto significa que, además de los atributos de cada entidad federativa, también contiene la geometría correspondiente a cada una de ellas. Entre las variables disponibles, la más importante para nuestros propósitos será <code>ENTIDAD</code>, ya que contiene el nombre de cada estado y nos servirá más adelante para unir la cartografía con la base de pobreza.</p>
<p>Si queremos echar un primer vistazo visual a la cartografía, podemos graficar únicamente la geometría:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_geometry</span>(mapa_mexico))</span></code></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/unnamed-chunk-4-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-1"><img src="https://alejandroromerog.github.io/blog/RComoSIG-Mapa/index_files/figure-html/unnamed-chunk-4-1.png" class="img-fluid figure-img" width="672"></a></p>
</figure>
</div>
</div>
</div>
<p>Este gráfico todavía es muy básico, pero nos permite comprobar rápidamente que la capa se importó correctamente y que la geometría de las entidades federativas luce razonable. El siguiente paso es importar el archivo de Excel que contiene la información de pobreza. Antes de leerlo, conviene revisar qué hojas contiene:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">excel_sheets</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Anexo estad”stico entidades 2022.xlsx"</span>)</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [1] "Contenido"                       "Estados Unidos Mexicanos"       
 [3] "Aguascalientes"                  "Baja California"                
 [5] "Baja California Sur"             "Campeche"                       
 [7] "Coahuila de Zaragoza"            "Colima"                         
 [9] "Chiapas"                         "Chihuahua"                      
[11] "Ciudad de México"                "Durango"                        
[13] "Guanajuato"                      "Guerrero"                       
[15] "Hidalgo"                         "Jalisco"                        
[17] "México"                          "Michoacán de Ocampo"            
[19] "Morelos"                         "Nayarit"                        
[21] "Nuevo León"                      "Oaxaca"                         
[23] "Puebla"                          "Querétaro"                      
[25] "Quintana Roo"                    "San Luis Potosí"                
[27] "Sinaloa"                         "Sonora"                         
[29] "Tabasco"                         "Tamaulipas"                     
[31] "Tlaxcala"                        "Veracruz de Ignacio de la Llave"
[33] "Yucatán"                         "Zacatecas"                      </code></pre>
</div>
</div>
<p>Al hacer esto veremos que el archivo no contiene una sola tabla con toda la información junta, sino varias hojas: una de contenido, una para el total nacional y una hoja para cada entidad federativa. Esta estructura no es tan cómoda como una base rectangular tradicional, pero sigue siendo perfectamente utilizable. De hecho, nos permitirá construir nosotros mismos una pequeña base de datos estatal a partir de cada hoja. Para entender mejor cómo está organizado el archivo, podemos importar primero una sola hoja, por ejemplo la de <strong>Aguascalientes</strong>:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">aguascalientes_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_excel</span>(</span>
<span id="cb9-2">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Anexo estad”stico entidades 2022.xlsx"</span>,</span>
<span id="cb9-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sheet =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Aguascalientes"</span>,</span>
<span id="cb9-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col_names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb9-5">)</span>
<span id="cb9-6"></span>
<span id="cb9-7">aguascalientes_raw</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 28 × 17
   ...1       ...2  ...3  ...4      ...5    ...6 ...7  ...8  ...9   ...10  ...11
   &lt;chr&gt;      &lt;lgl&gt; &lt;chr&gt; &lt;chr&gt;    &lt;dbl&gt;   &lt;dbl&gt; &lt;chr&gt; &lt;lgl&gt; &lt;chr&gt;  &lt;dbl&gt;  &lt;dbl&gt;
 1 Medición … NA    &lt;NA&gt;  &lt;NA&gt;    NA       NA    &lt;NA&gt;  NA    &lt;NA&gt;    NA     NA  
 2 Porcentaj… NA    &lt;NA&gt;  &lt;NA&gt;    NA       NA    &lt;NA&gt;  NA    &lt;NA&gt;    NA     NA  
 3 &lt;NA&gt;       NA    Indi… Porc…   NA       NA    &lt;NA&gt;  NA    Mile…   NA     NA  
 4 &lt;NA&gt;       NA    &lt;NA&gt;  2016  2018     2020    2022… NA    2016  2018   2020  
 5 &lt;NA&gt;       NA    Pobr… &lt;NA&gt;    NA       NA    &lt;NA&gt;  NA    &lt;NA&gt;    NA     NA  
 6 &lt;NA&gt;       NA    Pobl… 28.9…   26.3     27.6  23.7… NA    381.…  361.   396. 
 7 &lt;NA&gt;       NA    Pobl… 26.7…   25.3     25.2  21.9… NA    352.…  347.   362. 
 8 &lt;NA&gt;       NA    Pobl… 2.21…    0.988    2.42 1.75… NA    29.2…   13.6   34.7
 9 &lt;NA&gt;       NA    Pobl… 25.1…   25.5     25.6  29.8… NA    330.…  351.   367. 
10 &lt;NA&gt;       NA    Pobl… 11.5…   12.0     11.1  9.25… NA    152.…  165.   159. 
# ℹ 18 more rows
# ℹ 6 more variables: ...12 &lt;chr&gt;, ...13 &lt;lgl&gt;, ...14 &lt;chr&gt;, ...15 &lt;dbl&gt;,
#   ...16 &lt;dbl&gt;, ...17 &lt;chr&gt;</code></pre>
</div>
</div>
<p>Si observamos esta hoja con cuidado, notaremos que la fila que nos interesa es la correspondiente a <strong>Población en situación de pobreza</strong>, mientras que las columnas que nos interesan son las de los años <strong>2016, 2018, 2020 y 2022</strong> dentro del bloque de porcentajes. Es decir, lo que haremos a continuación será repetir esta misma extracción para cada una de las hojas estatales. Primero obtenemos los nombres de todas las hojas y descartamos aquellas que no representan una entidad federativa:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">hojas <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">excel_sheets</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Anexo estad”stico entidades 2022.xlsx"</span>)</span>
<span id="cb11-2"></span>
<span id="cb11-3">hojas_estados <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> hojas[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>(hojas <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Contenido"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Estados Unidos Mexicanos"</span>))]</span>
<span id="cb11-4"></span>
<span id="cb11-5">hojas_estados</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [1] "Aguascalientes"                  "Baja California"                
 [3] "Baja California Sur"             "Campeche"                       
 [5] "Coahuila de Zaragoza"            "Colima"                         
 [7] "Chiapas"                         "Chihuahua"                      
 [9] "Ciudad de México"                "Durango"                        
[11] "Guanajuato"                      "Guerrero"                       
[13] "Hidalgo"                         "Jalisco"                        
[15] "México"                          "Michoacán de Ocampo"            
[17] "Morelos"                         "Nayarit"                        
[19] "Nuevo León"                      "Oaxaca"                         
[21] "Puebla"                          "Querétaro"                      
[23] "Quintana Roo"                    "San Luis Potosí"                
[25] "Sinaloa"                         "Sonora"                         
[27] "Tabasco"                         "Tamaulipas"                     
[29] "Tlaxcala"                        "Veracruz de Ignacio de la Llave"
[31] "Yucatán"                         "Zacatecas"                      </code></pre>
</div>
</div>
<p>Ahora construiremos una pequeña función que lea cada hoja estatal, localice la fila de <strong>Población en situación de pobreza</strong> y extraiga el porcentaje correspondiente a 2016, 2018, 2020 y 2022, respectivamente. En este archivo, esa información se encuentra en la tercera columna para el nombre del indicador y en la cuarta, quinta, sexta y séptima columna para el porcentaje de los años ya mencionados.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">extraer_pobreza <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">function</span>(hoja) {</span>
<span id="cb13-2">  tabla <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_excel</span>(</span>
<span id="cb13-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Anexo estad”stico entidades 2022.xlsx"</span>,</span>
<span id="cb13-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sheet =</span> hoja,</span>
<span id="cb13-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col_names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb13-6">  )</span>
<span id="cb13-7">  </span>
<span id="cb13-8">  fila_pobreza <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(tabla[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Población en situación de pobreza"</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb13-9">  </span>
<span id="cb13-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb13-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ENTIDAD =</span> hoja,</span>
<span id="cb13-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pobreza_2016 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(tabla[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]][fila_pobreza]),</span>
<span id="cb13-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pobreza_2018 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(tabla[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]][fila_pobreza]),</span>
<span id="cb13-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pobreza_2020 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(tabla[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]][fila_pobreza]),</span>
<span id="cb13-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pobreza_2022 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(tabla[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]][fila_pobreza])</span>
<span id="cb13-16">  )</span>
<span id="cb13-17">}</span></code></pre></div>
</div>
<p>Con esa función lista, ya podemos aplicarla a todas las hojas estatales y reunir el resultado en una sola base:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">pobreza_estados <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bind_rows</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(hojas_estados, extraer_pobreza))</span>
<span id="cb14-2"></span>
<span id="cb14-3">pobreza_estados</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>                           ENTIDAD pobreza_2016 pobreza_2018 pobreza_2020
1                   Aguascalientes     28.94648     26.26541     27.62669
2                  Baja California     22.60487     23.59869     22.51012
3              Baja California Sur     22.88005     18.57216     27.60222
4                         Campeche     45.66019     48.96430     50.54915
5             Coahuila de Zaragoza     27.05571     25.50771     25.61704
6                           Colima     32.53320     30.41075     26.69353
7                          Chiapas     77.91276     77.99502     75.49129
8                        Chihuahua     30.70164     26.64279     25.30499
9                 Ciudad de México     26.59985     29.96781     32.60447
10                         Durango     37.19312     38.78717     38.69167
11                      Guanajuato     39.35110     41.48813     42.74239
12                        Guerrero     66.82816     67.89002     66.40571
13                         Hidalgo     56.90224     49.86971     50.75079
14                         Jalisco     30.46840     27.80150     31.41550
15                          México     46.64539     41.77450     48.86456
16             Michoacán de Ocampo     54.16250     46.21151     44.50929
17                         Morelos     46.69338     48.54414     50.94579
18                         Nayarit     38.10435     35.72054     30.40544
19                      Nuevo León     18.84034     19.38327     24.33040
20                          Oaxaca     67.97761     64.33596     61.66425
21                          Puebla     58.12609     58.00944     62.43210
22                       Querétaro     29.68809     26.37347     31.32530
23                    Quintana Roo     31.65285     30.19206     47.48029
24                 San Luis Potosí     44.13719     42.06817     42.84615
25                         Sinaloa     30.45804     30.98426     28.07140
26                          Sonora     27.00777     26.66402     29.92402
27                         Tabasco     53.84361     56.35136     54.47779
28                      Tamaulipas     32.04342     34.54683     34.94246
29                        Tlaxcala     55.93331     50.96552     59.28752
30 Veracruz de Ignacio de la Llave     60.49191     60.15534     58.60315
31                         Yucatán     45.50457     44.03003     49.48563
32                       Zacatecas     50.19457     49.23215     45.77076
   pobreza_2022
1      23.72232
2      13.37082
3      13.32903
4      45.12944
5      18.24332
6      20.54717
7      67.37083
8      17.57220
9      23.96761
10     34.31107
11     33.03430
12     60.35474
13     40.99902
14     21.83615
15     42.87551
16     41.73628
17     41.05589
18     29.31316
19     16.04045
20     58.44035
21     54.01727
22     21.69072
23     26.96601
24     35.52276
25     21.63881
26     21.69311
27     46.47409
28     26.82275
29     52.51998
30     51.73243
31     38.77263
32     44.21589</code></pre>
</div>
</div>
<p>En este punto ya contamos con una base de datos mucho más cómoda para trabajar los datos de pobreza. <code>pobreza_estados</code> tiene una fila por entidad federativa y una columna para cada año de interés. A primera vista, podría parecer que ya estamos listos para unir esta tabla con la cartografía. Sin embargo, antes de hacerlo conviene verificar que los nombres de las entidades coincidan correctamente en ambas fuentes. Podemos revisar rápidamente los nombres únicos de cada base con las siguientes instrucciones:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(mapa_mexico<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ENTIDAD))</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [1] "AGUASCALIENTES"                  "BAJA CALIFORNIA"                
 [3] "BAJA CALIFORNIA SUR"             "CAMPECHE"                       
 [5] "CHIAPAS"                         "CHIHUAHUA"                      
 [7] "COAHUILA DE ZARAGOZA"            "COLIMA"                         
 [9] "DISTRITO FEDERAL"                "DURANGO"                        
[11] "GUANAJUATO"                      "GUERRERO"                       
[13] "HIDALGO"                         "JALISCO"                        
[15] "MEXICO"                          "MICHOACAN DE OCAMPO"            
[17] "MORELOS"                         "NAYARIT"                        
[19] "NUEVO LEON"                      "OAXACA"                         
[21] "PUEBLA"                          "QUERETARO DE ARTEAGA"           
[23] "QUINTANA ROO"                    "SAN LUIS POTOSI"                
[25] "SINALOA"                         "SONORA"                         
[27] "TABASCO"                         "TAMAULIPAS"                     
[29] "TLAXCALA"                        "VERACRUZ DE IGNACIO DE LA LLAVE"
[31] "YUCATAN"                         "ZACATECAS"                      </code></pre>
</div>
<div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(pobreza_estados<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ENTIDAD))</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [1] "Aguascalientes"                  "Baja California"                
 [3] "Baja California Sur"             "Campeche"                       
 [5] "Chiapas"                         "Chihuahua"                      
 [7] "Ciudad de México"                "Coahuila de Zaragoza"           
 [9] "Colima"                          "Durango"                        
[11] "Guanajuato"                      "Guerrero"                       
[13] "Hidalgo"                         "Jalisco"                        
[15] "México"                          "Michoacán de Ocampo"            
[17] "Morelos"                         "Nayarit"                        
[19] "Nuevo León"                      "Oaxaca"                         
[21] "Puebla"                          "Querétaro"                      
[23] "Quintana Roo"                    "San Luis Potosí"                
[25] "Sinaloa"                         "Sonora"                         
[27] "Tabasco"                         "Tamaulipas"                     
[29] "Tlaxcala"                        "Veracruz de Ignacio de la Llave"
[31] "Yucatán"                         "Zacatecas"                      </code></pre>
</div>
</div>
<p>Si observamos ambas salidas con cuidado, veremos que los nombres no coinciden de forma exacta. Esto ocurre porque la cartografía de CONABIO utiliza mayúsculas, omite algunos acentos y además conserva nombres administrativos más antiguos, como <code>DISTRITO FEDERAL</code>; mientras que el archivo de pobreza usa nombres más recientes, como <code>Ciudad de México</code>. Para resolver este problema, crearemos una pequeña función que estandarice los nombres de las entidades en ambas bases.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1">normalizar_entidad <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">function</span>(x) {</span>
<span id="cb20-2">  x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stri_trans_general</span>(x, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Latin-ASCII"</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina acentos</span></span>
<span id="cb20-3">  x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toupper</span>(x) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convierte a mayúsculas</span></span>
<span id="cb20-4">  x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">trimws</span>(x) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina espacios en blanco al inicio y al final</span></span>
<span id="cb20-5">  </span>
<span id="cb20-6">  x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>( <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Reemplaza nombres específicos</span></span>
<span id="cb20-7">    x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"DISTRITO FEDERAL"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"CIUDAD DE MEXICO"</span>,</span>
<span id="cb20-8">    x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QUERETARO DE ARTEAGA"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QUERETARO"</span>,</span>
<span id="cb20-9">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> x</span>
<span id="cb20-10">  )</span>
<span id="cb20-11">  </span>
<span id="cb20-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(x)</span>
<span id="cb20-13">}</span></code></pre></div>
</div>
<p>Aplicamos ahora esta función tanto a la cartografía como a la base de pobreza:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">mapa_mexico <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mapa_mexico <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb21-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ENTIDAD_STD =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">normalizar_entidad</span>(ENTIDAD))</span>
<span id="cb21-3"></span>
<span id="cb21-4">pobreza_estados <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> pobreza_estados <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb21-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ENTIDAD_STD =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">normalizar_entidad</span>(ENTIDAD))</span></code></pre></div>
</div>
<p>Con esto ya podemos unir ambas fuentes de información utilizando la nueva variable <code>ENTIDAD_STD</code> como llave:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">mapa_pobreza <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mapa_mexico <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb22-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">left_join</span>(</span>
<span id="cb22-3">    pobreza_estados <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb22-4">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(ENTIDAD_STD, pobreza_2016, pobreza_2018, pobreza_2020, pobreza_2022),</span>
<span id="cb22-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ENTIDAD_STD"</span></span>
<span id="cb22-6">  )</span></code></pre></div>
</div>
</section>
<section id="construcción-de-mapas-coropléticos" class="level2">
<h2 class="anchored" data-anchor-id="construcción-de-mapas-coropléticos">Construcción de mapas coropléticos</h2>
<p>Ahora pasemos a la parte más visual del tutorial. Como ya tenemos la geometría de cada entidad y el porcentaje de población en pobreza para varios años dentro de un mismo objeto <code>sf</code>, podemos comenzar construyendo un primer mapa para 2016. La lógica de <code>{ggplot2}</code> en este caso es bastante simple: usaremos <code>geom_sf()</code> para dibujar las entidades federativas y asignaremos la variable <code>pobreza_2016</code> al argumento <code>fill</code>, que controla el color de relleno de cada polígono.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1">mapa_2016 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(mapa_pobreza) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_sf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> pobreza_2016), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_gradient</span>(</span>
<span id="cb23-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#FDFBF7"</span>,</span>
<span id="cb23-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#9158A2"</span>,</span>
<span id="cb23-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pobreza (%)"</span></span>
<span id="cb23-7">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb23-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Porcentaje de población en situación de pobreza por entidad federativa"</span>,</span>
<span id="cb23-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"México, 2016"</span>,</span>
<span id="cb23-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fuente: Elaboración propia con datos de CONEVAL y geometrías de CONABIO"</span></span>
<span id="cb23-12">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_void</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb23-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb23-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>),</span>
<span id="cb23-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>),</span>
<span id="cb23-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>),</span>
<span id="cb23-18">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span></span>
<span id="cb23-19">  )</span>
<span id="cb23-20"></span>
<span id="cb23-21">mapa_2016</span></code></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/unnamed-chunk-14-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2"><img src="https://alejandroromerog.github.io/blog/RComoSIG-Mapa/index_files/figure-html/unnamed-chunk-14-1.png" class="img-fluid figure-img" width="672"></a></p>
</figure>
</div>
</div>
</div>
<p>El resultado es ya un mapa coroplético funcional: cada estado aparece coloreado según su porcentaje de población en situación de pobreza. Los tonos más claros representan menores niveles de pobreza, mientras que los tonos más intensos corresponden a valores más altos. Una ventaja adicional de haber extraído los datos para más de un año es que podemos repetir este mismo procedimiento para 2018, 2020 o 2022, simplemente cambiando la variable utilizada en <code>fill</code>. Por ejemplo, para mapear 2022 bastaría con reemplazar <code>pobreza_2016</code> por <code>pobreza_2022</code> y cambiar el subtítulo:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1">mapa_2022 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(mapa_pobreza) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb24-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_sf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> pobreza_2022), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb24-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_gradient</span>(</span>
<span id="cb24-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#FDFBF7"</span>,</span>
<span id="cb24-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#9158A2"</span>,</span>
<span id="cb24-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pobreza (%)"</span></span>
<span id="cb24-7">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb24-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb24-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Porcentaje de población en situación de pobreza por entidad federativa"</span>,</span>
<span id="cb24-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"México, 2022"</span>,</span>
<span id="cb24-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fuente: Elaboración propia con datos de CONEVAL y geometrías de CONABIO"</span></span>
<span id="cb24-12">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb24-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_void</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb24-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb24-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>),</span>
<span id="cb24-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>),</span>
<span id="cb24-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>),</span>
<span id="cb24-18">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"right"</span></span>
<span id="cb24-19">  )</span>
<span id="cb24-20"></span>
<span id="cb24-21">mapa_2022</span></code></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/unnamed-chunk-15-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3"><img src="https://alejandroromerog.github.io/blog/RComoSIG-Mapa/index_files/figure-html/unnamed-chunk-15-1.png" class="img-fluid figure-img" width="672"></a></p>
</figure>
</div>
</div>
</div>
<p>A bote pronto, con fines de comparación, podríamos poner una imagen al lado de la otra en cualquier documento para sacar conclusiones. Sin embargo, estaríamos cometiendo un error común en la visualización de datos: comparar mapas coropléticos sin una escala de colores común. En el ejemplo anterior, cada mapa tiene su propia escala de colores, lo que puede llevar a interpretaciones erróneas. Por ejemplo, un estado que tenga el mismo porcentaje de población en situación de pobreza en ambos años podría aparecer con un color diferente si las escalas no son idénticas (los valores mínimos y máximos cambian), lo que podría hacer pensar que hubo un cambio cuando en realidad no lo hubo. Para evitar esto, es fundamental establecer una escala de colores común para todos los mapas que se quieran comparar.</p>
<p>Para resolver este problema, primero debemos calcular un rango común de valores que abarque todos los años que queremos comparar. De esta manera, cada color representará exactamente el mismo nivel de pobreza en todos los mapas.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1">limites_pobreza <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(</span>
<span id="cb25-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(</span>
<span id="cb25-3">    mapa_pobreza<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pobreza_2016,</span>
<span id="cb25-4">    mapa_pobreza<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pobreza_2018,</span>
<span id="cb25-5">    mapa_pobreza<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pobreza_2020,</span>
<span id="cb25-6">    mapa_pobreza<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pobreza_2022</span>
<span id="cb25-7">  ),</span>
<span id="cb25-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span></span>
<span id="cb25-9">)</span>
<span id="cb25-10"></span>
<span id="cb25-11">limites_pobreza</span></code></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 13.32903 77.99502</code></pre>
</div>
</div>
<p>En lugar de construir cada mapa por separado y luego intentar acomodarlos manualmente, una alternativa más elegante consiste en reorganizar la base de datos a un formato largo. Así, cada observación conservará su geometría, pero además tendrá una nueva variable que indique el año correspondiente. Esto nos permitirá utilizar <code>facet_wrap()</code> para generar los cuatro mapas dentro de una sola figura. Para esto, usaremos la función <code>pivot_longer()</code> del paquete <code>{tidyr}</code>:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1">mapa_pobreza_largo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mapa_pobreza <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb27-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(geometry, pobreza_2016, pobreza_2018, pobreza_2020, pobreza_2022) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb27-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pivot_longer</span>(</span>
<span id="cb27-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cols =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">starts_with</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pobreza_"</span>),</span>
<span id="cb27-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names_to =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"anio"</span>,</span>
<span id="cb27-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values_to =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pobreza"</span></span>
<span id="cb27-7">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb27-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(</span>
<span id="cb27-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">anio =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(</span>
<span id="cb27-10">      anio,</span>
<span id="cb27-11">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pobreza_2016"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pobreza_2018"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pobreza_2020"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pobreza_2022"</span>),</span>
<span id="cb27-12">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2016"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2018"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2020"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2022"</span>)</span>
<span id="cb27-13">    )</span>
<span id="cb27-14">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb27-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_as_sf</span>()</span></code></pre></div>
</div>
<p>Con esta nueva base ya podemos construir una sola imagen con los cuatro mapas en una disposición de 2 por 2: en la primera fila aparecerán 2016 y 2018, y en la segunda 2020 y 2022.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1">mapa_comparativo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(mapa_pobreza_largo) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_sf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> pobreza), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_gradient</span>(</span>
<span id="cb28-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#FDFBF7"</span>,</span>
<span id="cb28-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#9158A2"</span>,</span>
<span id="cb28-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> limites_pobreza,</span>
<span id="cb28-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pobreza (%)"</span></span>
<span id="cb28-8">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span>anio, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb28-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Porcentaje de población en situación de pobreza por entidad federativa"</span>,</span>
<span id="cb28-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"México, 2016-2022"</span>,</span>
<span id="cb28-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fuente: Elaboración propia con datos de CONEVAL y geometrías de CONABIO"</span></span>
<span id="cb28-14">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_void</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb28-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>),</span>
<span id="cb28-18">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>),</span>
<span id="cb28-19">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>),</span>
<span id="cb28-20">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.caption =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>),</span>
<span id="cb28-21">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span></span>
<span id="cb28-22">  )</span>
<span id="cb28-23"></span>
<span id="cb28-24">mapa_comparativo</span></code></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><a href="index_files/figure-html/unnamed-chunk-18-1.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4"><img src="https://alejandroromerog.github.io/blog/RComoSIG-Mapa/index_files/figure-html/unnamed-chunk-18-1.png" class="img-fluid figure-img" width="672"></a></p>
</figure>
</div>
</div>
</div>
<p>El resultado es una sola figura comparativa con una escala de colores común, una sola leyenda y un encabezado compartido. De esta manera, cualquier diferencia visual entre los paneles refleja cambios reales en la pobreza y no simples variaciones en la escala de color. Finalmente, para guardar la visualización como archivo de imagen utilizaremos la función <code>ggsave()</code>, que permite exportar objetos creados con <code>{ggplot2}</code> en distintos formatos:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggsave</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">filename =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mapa.png"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot =</span> mapa_comparativo,</span>
<span id="cb29-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dpi =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bg =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>)</span></code></pre></div>
</div>
<p>Si preferimos guardarla como JPG, basta con cambiar la extensión del archivo:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggsave</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">filename =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mapa.jpg"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot =</span> mapa_comparativo,</span>
<span id="cb30-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dpi =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bg =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>)</span></code></pre></div>
</div>
<p>En ambos casos, <code>width</code> y <code>height</code> controlan el tamaño de la imagen, mientras que <code>dpi</code> determina su resolución. Un valor de 300 en este último campo suele ser suficiente para obtener una imagen de buena calidad tanto en pantalla como en impresión.</p>
</section>
<section id="conclusión" class="level2">
<h2 class="anchored" data-anchor-id="conclusión">Conclusión</h2>
<p>A lo largo de este tutorial vimos que R puede utilizarse como un Sistema de Información Geográfica bastante potente. Primero entendimos qué es un SIG y repasamos la diferencia entre Shapefiles y GeoPackages, dos de los formatos vectoriales más comunes en el trabajo geoespacial. Después importamos una capa cartográfica, construimos una base de datos estatal de pobreza a partir de un archivo de Excel, estandarizamos nombres de entidades, unimos ambas fuentes y, finalmente, creamos un mapa coroplético comparativo para distintos años.</p>
<p>Más allá de los mapas en sí, lo más importante aquí fue el flujo de trabajo que aprendimos: importar datos espaciales, limpiar datos tabulares, unir ambas fuentes y visualizarlas correctamente. Una vez entendido este proceso, resulta relativamente sencillo repetirlo con otras variables, otras escalas geográficas o incluso otras fuentes de información. En ese sentido, R no solo sirve para hacer mapas, sino para integrar análisis espacial y análisis de datos dentro de un mismo entorno de trabajo.</p>


</section>

 ]]></description>
  <category>R</category>
  <category>Tutorial</category>
  <category>Visualización</category>
  <category>Mapas</category>
  <guid>https://alejandroromerog.github.io/blog/RComoSIG-Mapa/</guid>
  <pubDate>Fri, 13 Mar 2026 06:00:00 GMT</pubDate>
  <media:content url="https://alejandroromerog.github.io/blog/RComoSIG-Mapa/mapa.png" medium="image" type="image/png" height="103" width="144"/>
</item>
<item>
  <title>Política de Drogas en Sin Filtro de N+</title>
  <link>https://alejandroromerog.github.io/blog/SinFiltroPoliticaDrogas/</link>
  <description><![CDATA[ 





<p><a href="https://www.nmas.com.mx/foro-tv/programas/sin-filtro/episodios/sin-filtro-programa-completo-domingo-4-febrero-2024/" class="btn"><i class="fa-solid fa-circle-play" aria-label="circle-play"></i> &nbsp;Ver Programa Completo</a></p>
<p>El 04 de febrero de 2024, tuve el honor de participar en el programa <em>Sin Filtro</em> de N+, conducido por Natalia Sánchez. El tema del programa fue la Política de Drogas y las problemáticas relacionadas con la regulación y la seguridad en México. En este episodio abordamos cuestiones cruciales como la regulación del fentanilo, la marihuana y los vapeadores.</p>
<p>Durante mi participación, presenté evidencia empírica y ofrecí perspectivas globales sobre estas sustancias. Además, realicé una revisión histórica del prohibicionismo en México, subrayando la importancia de adoptar un enfoque informado y basado en la reducción de daños para abordar estos complejos problemas. El panel estuvo compuesto por destacados jóvenes expertas y expertos, entre ellas Kinari Bustos, Jeter Peralta y José Ángel Bazán, quienes también compartieron sus valiosas opiniones y experiencias sobre el tema.</p>
<p>Puedes ver el episodio completo haciendo clic en el botón de arriba. Agradezco a Natalia Sánchez y a todo el equipo de <em>Sin Filtro</em> por la invitación y la oportunidad de participar en este importante programa. ¡Espero que disfrutes la discusión!</p>



 ]]></description>
  <category>Política de Drogas</category>
  <category>Regulación</category>
  <category>Seguridad</category>
  <category>TV</category>
  <guid>https://alejandroromerog.github.io/blog/SinFiltroPoliticaDrogas/</guid>
  <pubDate>Sun, 04 Feb 2024 06:00:00 GMT</pubDate>
  <media:content url="https://alejandroromerog.github.io/blog/SinFiltroPoliticaDrogas/SinFiltro20240204.png" medium="image" type="image/png" height="59" width="144"/>
</item>
<item>
  <title>Implementación de los Autómatas Celulares de Wolfram en R</title>
  <link>https://alejandroromerog.github.io/blog/ACW/</link>
  <description><![CDATA[ 
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs/loader.js"></script>
<script type="module" id="qwebr-monaco-editor-init">

  // Configure the Monaco Editor's loader
  require.config({
    paths: {
      'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs'
    }
  });
</script>
<script type="module">
// Global dictionary to store Monaco Editor instances
globalThis.qwebrEditorInstances = {};

// Function that builds and registers a Monaco Editor instance    
globalThis.qwebrCreateMonacoEditorInstance = function (cellData) {

  const initialCode = cellData.code;
  const qwebrCounter = cellData.id;

  // Retrieve the previously created document elements
  let runButton = document.getElementById(`qwebr-button-run-${qwebrCounter}`);
  let editorDiv = document.getElementById(`qwebr-editor-${qwebrCounter}`);
  
  // Load the Monaco Editor and create an instance
  let editor;
  require(['vs/editor/editor.main'], function () {
    editor = monaco.editor.create(editorDiv, {
      value: initialCode,
      language: 'r',
      theme: 'vs-light',
      automaticLayout: true,           // Works wonderfully with RevealJS
      scrollBeyondLastLine: false,
      minimap: {
        enabled: false
      },
      fontSize: '17.5pt',              // Bootstrap is 1 rem
      renderLineHighlight: "none",     // Disable current line highlighting
      hideCursorInOverviewRuler: true  // Remove cursor indictor in right hand side scroll bar
    });

    // Store the official counter ID to be used in keyboard shortcuts
    editor.__qwebrCounter = qwebrCounter;

    // Store the official div container ID
    editor.__qwebrEditorId = `qwebr-editor-${qwebrCounter}`;

    // Store the initial code value
    editor.__qwebrinitialCode = initialCode;

    // Set at the model level the preferred end of line (EOL) character to LF.
    // This prevent `\r\n` from being given to the webR engine if the user is on Windows.
    // See details in: https://github.com/coatless/quarto-webr/issues/94
    // Associated error text: 
    // Error: <text>:1:7 unexpected input

    // Retrieve the underlying model
    const model = editor.getModel();
    // Set EOL for the model
    model.setEOL(monaco.editor.EndOfLineSequence.LF);

    // Dynamically modify the height of the editor window if new lines are added.
    let ignoreEvent = false;
    const updateHeight = () => {
      const contentHeight = editor.getContentHeight();
      // We're avoiding a width change
      //editorDiv.style.width = `${width}px`;
      editorDiv.style.height = `${contentHeight}px`;
      try {
        ignoreEvent = true;

        // The key to resizing is this call
        editor.layout();
      } finally {
        ignoreEvent = false;
      }
    };

    // Helper function to check if selected text is empty
    function isEmptyCodeText(selectedCodeText) {
      return (selectedCodeText === null || selectedCodeText === undefined || selectedCodeText === "");
    }

    // Registry of keyboard shortcuts that should be re-added to each editor window
    // when focus changes.
    const addWebRKeyboardShortCutCommands = () => {
      // Add a keydown event listener for Shift+Enter to run all code in cell
      editor.addCommand(monaco.KeyMod.Shift | monaco.KeyCode.Enter, () => {

        // Retrieve all text inside the editor
        qwebrExecuteCode(editor.getValue(), editor.__qwebrCounter);
      });

      // Add a keydown event listener for CMD/Ctrl+Enter to run selected code
      editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () => {

        // Get the selected text from the editor
        const selectedText = editor.getModel().getValueInRange(editor.getSelection());
        // Check if no code is selected
        if (isEmptyCodeText(selectedText)) {
          // Obtain the current cursor position
          let currentPosition = editor.getPosition();
          // Retrieve the current line content
          let currentLine = editor.getModel().getLineContent(currentPosition.lineNumber);

          // Propose a new position to move the cursor to
          let newPosition = new monaco.Position(currentPosition.lineNumber + 1, 1);

          // Check if the new position is beyond the last line of the editor
          if (newPosition.lineNumber > editor.getModel().getLineCount()) {
            // Add a new line at the end of the editor
            editor.executeEdits("addNewLine", [{
            range: new monaco.Range(newPosition.lineNumber, 1, newPosition.lineNumber, 1),
            text: "\n", 
            forceMoveMarkers: true,
            }]);
          }
          
          // Run the entire line of code.
          qwebrExecuteCode(currentLine, editor.__qwebrCounter,
            EvalTypes.Interactive);

          // Move cursor to new position
          editor.setPosition(newPosition);
        } else {
          // Code to run when Ctrl+Enter is pressed with selected code
          qwebrExecuteCode(selectedText, editor.__qwebrCounter, EvalTypes.Interactive);
        }
      });
    }

    // Register an on focus event handler for when a code cell is selected to update
    // what keyboard shortcut commands should work.
    // This is a workaround to fix a regression that happened with multiple
    // editor windows since Monaco 0.32.0 
    // https://github.com/microsoft/monaco-editor/issues/2947
    editor.onDidFocusEditorText(addWebRKeyboardShortCutCommands);

    // Register an on change event for when new code is added to the editor window
    editor.onDidContentSizeChange(updateHeight);

    // Manually re-update height to account for the content we inserted into the call
    updateHeight();

    // Store the editor instance in the global dictionary
    qwebrEditorInstances[editor.__qwebrCounter] = editor;

  });

  // Add a click event listener to the run button
  runButton.onclick = function () {
    qwebrExecuteCode(editor.getValue(), editor.__qwebrCounter, EvalTypes.Interactive);
  };

}
</script>





<section id="introducción-a-los-autómatas-celulares-de-wolfram" class="level2">
<h2 class="anchored" data-anchor-id="introducción-a-los-autómatas-celulares-de-wolfram">Introducción a los Autómatas Celulares (de Wolfram)</h2>
<p>Los Autómatas Celulares (AC) son sistemas dinámicos discretos y abstractos con aplicaciones en numerosos campos científicos. Se componen de una red de <em>células</em> que cambian de estado según reglas determinadas, a menudo con base en el estado de las células vecinas. Esta sencilla premisa puede generar una sorprendente variedad de comportamientos: desde patrones estáticos, hasta dinámicas complejas y caóticas.</p>
<p>Los AC fueron introducidos por primera vez por el matemático <a href="https://en.wikipedia.org/wiki/John_von_Neumann">John von Neumann</a> y el físico <a href="https://en.wikipedia.org/wiki/Stanis%C5%82aw_Ulam">Stanislaw Ulam</a> en la década de 1960, pero fue el físico <a href="https://en.wikipedia.org/wiki/Stephen_Wolfram">Stephen Wolfram</a> quien popularizó su estudio en la década de 1980. Wolfram propuso una estructura unidimensional y un conjunto de reglas binarias simples para los AC, que se terminaron conociendo como los Autómatas Celulares de Wolfram (ACW). Este tipo de autómatas se han convertido en un modelo de referencia para el estudio de la complejidad y la emergencia de patrones en sistemas dinámicos.</p>
<section id="fundamentos-teóricos" class="level3">
<h3 class="anchored" data-anchor-id="fundamentos-teóricos">Fundamentos Teóricos</h3>
<p>En general, los AC basan su comportamiento en tres componentes principales:</p>
<ul>
<li><strong>Espacio de Células</strong>: Una matriz (en nuestro caso, un vector) donde cada elemento representa una célula.</li>
<li><strong>Estados</strong>: Cada célula puede adoptar un estado de un conjunto finito de estados posibles. En este ejemplo, las células pueden estar activas (“<img src="https://latex.codecogs.com/png.latex?1">”) o inactivas (“<img src="https://latex.codecogs.com/png.latex?0">”).</li>
<li><strong>Reglas de Evolución</strong>: Las células cambian de estado según reglas determinadas, habitualmente con base en el estado de las células vecinas. Para los ACW, las células cambian de estado basandose en su propio estado y el de las células que están a la izquierda y derecha de cada una de ellas mediante una regla binaria de 8 bits. Esta última se representa como un número entero entre 0 y 255.</li>
</ul>
</section>
</section>
<section id="preparación-del-entorno-en-r" class="level2">
<h2 class="anchored" data-anchor-id="preparación-del-entorno-en-r">Preparación del Entorno en R</h2>
<p>Para comenzar nuestra exploración de los Autómatas Celulares de Wolfram en R, primero necesitamos configurar nuestro entorno de trabajo cargando algunas bibliotecas esenciales. Estas bibliotecas nos ayudarán en la manipulación de datos y en la visualización gráfica de los resultados.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Instalalas si aún no las tienes utilizando:</span></span>
<span id="cb1-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># install.packages(c("dplyr", "ggplot2", "ggview"))</span></span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(dplyr) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para la manipulación de datos</span></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para la creación de gráficos</span></span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggview) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># para visualizar los gráficos en el Viewer sin guardarlos</span></span></code></pre></div>
</div>
</section>
<section id="definición-de-la-función-para-reglas-binarias" class="level2">
<h2 class="anchored" data-anchor-id="definición-de-la-función-para-reglas-binarias">Definición de la Función para Reglas Binarias</h2>
<p>Después de haber preparado nuestro entorno en R, el siguiente paso es definir cómo nuestro ACW interpretará las reglas que dictarán la evolución de sus células. Recordemos que en los ACW, estas reglas se aplican basándose en el estado actual de una célula y sus vecinos inmediatos a la izquierda y a la derecha.</p>
<p>Cada combinación de estos tres estados (el propio y los de sus dos vecinos) puede ser representada como un número binario de 3 dígitos, y para cada combinación posible, la regla del autómata define si la célula estará activa o inactiva en la siguiente generación. Dado que hay <img src="https://latex.codecogs.com/png.latex?2%5E%7B3%7D%20=%208"> combinaciones posibles, una regla de autómata celular se puede representar como una secuencia de 8 bits, donde cada bit indica el estado resultante para una combinación específica de vecinos. Por lo tanto, hay un total de <img src="https://latex.codecogs.com/png.latex?2%5E%7B8%7D%20=%20256"> reglas posibles, numeradas del 0 al 255.</p>
<p>La función <code>getBinaryRule</code> que definiremos a continuación, toma un número entre 0 y 255 y lo convierte en su versión binaria de 8 bits. Aquí nos estamos aprovechando de que los números del 0 al 255 se representan en binario con 8 dígitos y a partir del 256 con 9 o más. Esto nos permitirá aplicar fácilmente la regla elegida a nuestro autómata:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">getBinaryRule <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">function</span>(ruleNumber) {</span>
<span id="cb2-2">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convierte el número en una secuencia de bits:</span></span>
<span id="cb2-3">  ruleBinary <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">intToBits</span>(ruleNumber)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>]</span>
<span id="cb2-4">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convierte la secuencia de bits en un vector de enteros:</span></span>
<span id="cb2-5">  ruleBinary <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(ruleBinary))</span>
<span id="cb2-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(ruleBinary)</span>
<span id="cb2-7">}</span></code></pre></div>
</div>
<p>Tras definir la función <code>getBinaryRule</code>, nuestro siguiente paso es establecer el escenario para la simulación de nuestro ACW. Esto implica inicializar las reglas que determinarán el comportamiento de las células y preparar la población inicial en nuestro modelo.</p>
</section>
<section id="inicialización-de-las-reglas-y-las-células" class="level2">
<h2 class="anchored" data-anchor-id="inicialización-de-las-reglas-y-las-células">Inicialización de las Reglas y las Células</h2>
<p>Comenzaremos eligiendo una regla específica para nuestro autómata. Recordemos que las reglas varían de 0 a 255, cada una produciendo patrones interesantes. Para este ejemplo, utilizaremos la regla 135:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Selecciona la regla número 135:</span></span>
<span id="cb3-2">ruleNumber <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">135</span></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convierte la regla a su representación binaria:</span></span>
<span id="cb3-4">ruleSet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getBinaryRule</span>(ruleNumber)</span>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Establece el número de células y generaciones para la simulación:</span></span>
<span id="cb3-6">numCells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span></span>
<span id="cb3-7">generations <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span></span>
<span id="cb3-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Crea una matriz para representar cada generación de células:</span></span>
<span id="cb3-9">grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> generations, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> numCells)</span></code></pre></div>
</div>
</section>
<section id="configuración-de-la-población-inicial" class="level2">
<h2 class="anchored" data-anchor-id="configuración-de-la-población-inicial">Configuración de la Población Inicial</h2>
<p>Ahora, definiremos la población inicial de células. Para simplificar y visualizar claramente el efecto de la regla seleccionada, iniciaremos con una única célula activa en el centro de nuestra cuadrícula:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Inicializa todas las células en estado inactivo (0):</span></span>
<span id="cb4-2">cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, numCells)</span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Activa la célula central:</span></span>
<span id="cb4-4">cells[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(numCells <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Establece la configuración previa como la primera generación en nuestra matriz:</span></span>
<span id="cb4-6">grid[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cells</span></code></pre></div>
</div>
<p>Así, estamos en posición de simular cómo estas células evolucionarán a lo largo de las generaciones bajo la regla seleccionada. Este es el núcleo de los ACW, donde las simples reglas locales conducen a patrones complejos y a menudo sorprendentes a lo largo del tiempo.</p>
</section>
<section id="aplicación-de-las-reglas-para-dar-paso-a-nuevas-generaciones" class="level2">
<h2 class="anchored" data-anchor-id="aplicación-de-las-reglas-para-dar-paso-a-nuevas-generaciones">Aplicación de las Reglas para Dar Paso a Nuevas Generaciones</h2>
<p>Para observar la evolución de nuestro autómata celular, aplicaremos las reglas definidas en cada célula y en cada generación. Recordemos que las reglas consideran el estado de una célula y sus vecinas inmediatas (izquierda y derecha) para determinar su nuevo estado. Este proceso se repite para cada célula en cada nueva generación:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Bucle a través de cada generación, empezando por la segunda:</span></span>
<span id="cb5-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">for</span> (gen <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>generations) {</span>
<span id="cb5-3">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Bucle a través de cada célula en la generación:</span></span>
<span id="cb5-4">  <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>numCells) {</span>
<span id="cb5-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calcula los índices de las vecinas izquierda y derecha, </span></span>
<span id="cb5-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># considerando condiciones de frontera periódicas</span></span>
<span id="cb5-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (si la célula está en el borde, la vecina es la primera o la última):</span></span>
<span id="cb5-8">    left_index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, numCells, i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-9">    right_index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> numCells, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-10"></span>
<span id="cb5-11">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Obtiene los estados de las vecinas y de la célula central:</span></span>
<span id="cb5-12">    left <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid[gen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, left_index]</span>
<span id="cb5-13">    center <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid[gen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, i]</span>
<span id="cb5-14">    right <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid[gen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, right_index]</span>
<span id="cb5-15"></span>
<span id="cb5-16">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calcula el patrón de vecindario en versión entera (nota más adelante):</span></span>
<span id="cb5-17">    neighborhood <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> left <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> center <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> right</span>
<span id="cb5-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Determina el nuevo estado basado en la respectiva regla:</span></span>
<span id="cb5-19">    grid[gen, i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ruleSet[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> neighborhood]</span>
<span id="cb5-20">  }</span>
<span id="cb5-21">}</span></code></pre></div>
</div>
<div class="callout callout-style-default callout-tip callout-titled" title="Nota">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Nota
</div>
</div>
<div class="callout-body-container callout-body">
<p>El vecindario de una célula es una combinación de sus estados y los de sus dos vecinas. En los ACW, este vecindario se representa como un número binario de 3 dígitos. Por ejemplo, si la célula izquierda, la célula central y la célula derecha están en los estados 1 (activo), 0 (inactivo), y 1 (activo), respectivamente, el vecindario se representa como <img src="https://latex.codecogs.com/png.latex?101"> en binario.</p>
<p>Para convertir esta representación binaria del vecindario en algo que podamos usar para acceder a nuestra regla en versión binaria, necesitamos convertirla a un número entero que vaya del 0 al 7. Aquí es donde entran en juego las multiplicaciones por 4 y por 2:</p>
<ul>
<li>El bit más a la izquierda (la vecina izquierda) se multiplica por 4 porque, en la representación binaria, este bit es equivalente a <img src="https://latex.codecogs.com/png.latex?2%5E%7B2%7D%20=%204">. Si este bit es 1, su contribución al número decimal total es 4.</li>
<li>El bit del medio (la célula misma) se multiplica por 2 porque corresponde a <img src="https://latex.codecogs.com/png.latex?2%5E%7B1%7D%20=%202"> en binario. Si esta célula está activa, añade 2 al número decimal.</li>
<li>El bit más a la derecha (la vecina derecha) no se multiplica porque representa <img src="https://latex.codecogs.com/png.latex?2%5E%7B0%7D%20=%201">. Así, su estado (activo o inactivo) se añade tal cual al número decimal.</li>
</ul>
</div>
</div>
<p>Este doble bucle, primero a través de las generaciones y luego a través de cada célula, es el corazón de nuestra simulación. En cada paso, estamos aplicando cada regla binaria para determinar el estado futuro de cada célula, basándonos en su estado actual y el de sus vecinas. Al final de este proceso, tendremos una representación completa de cómo las células evolucionan a lo largo del tiempo bajo la influencia de nuestra regla seleccionada.</p>
</section>
<section id="visualización-de-la-evolución-de-las-células" class="level2">
<h2 class="anchored" data-anchor-id="visualización-de-la-evolución-de-las-células">Visualización de la Evolución de las Células</h2>
<p>Para visualizar la evolución de nuestro ACW, primero necesitamos transformar nuestros datos de la matriz <code>grid</code> en un formato adecuado para <code>{ggplot2}</code>. Lo hacemos creando un <em>data frame</em> que represente cada célula y su estado en cada generación:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Crea un data frame con todas las combinaciones de células y generaciones:</span></span>
<span id="cb6-2">df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>numCells, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>generations)</span>
<span id="cb6-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Asigna los valores de la cuadrícula al data frame, ajustando la estructura.</span></span>
<span id="cb6-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># La transposición cambia las filas por columnas y viceversa para que cada</span></span>
<span id="cb6-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># columna represente una generación y cada fila una célula.</span></span>
<span id="cb6-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># La función as.vector() convierte la matriz en un vector para que podamos ir</span></span>
<span id="cb6-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># asignando valores de generación en generación, como esta creado el data frame:</span></span>
<span id="cb6-8">df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(grid))</span>
<span id="cb6-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Ajusta el eje y para que las generaciones se muestren en el orden correcto</span></span>
<span id="cb6-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (de arriba a abajo):</span></span>
<span id="cb6-11">df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> generations <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span></code></pre></div>
</div>
<p>Ahora que tenemos nuestros datos en el formato correcto, podemos proceder a visualizarlos utilizando <code>{ggplot2}</code>. Esta herramienta nos permite crear una representación gráfica clara y atractiva de cómo cambian las células a lo largo del tiempo:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Crea un gráfico con ggplot2:</span></span>
<span id="cb7-2">plot_acw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(value))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_tile</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Crea un gráfico de mosaico</span></span>
<span id="cb7-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define los colores</span></span>
<span id="cb7-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina la leyenda</span></span>
<span id="cb7-6">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina las líneas de la cuadrícula</span></span>
<span id="cb7-7">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina los títulos de los ejes</span></span>
<span id="cb7-8">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina las etiquetas de los ejes</span></span>
<span id="cb7-9">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.ticks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina las marcas de los ejes</span></span>
<span id="cb7-10">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina el fondo del panel</span></span>
<span id="cb7-11">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.border =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>()) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Elimina el borde del panel</span></span>
<span id="cb7-12"></span>
<span id="cb7-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Visualiza el gráfico en el Viewer de RStudio:</span></span>
<span id="cb7-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#ggview(plot_acw, width=10, height = 10, dpi = 500, units = "in")</span></span>
<span id="cb7-15"></span>
<span id="cb7-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Guarda el gráfico como un archivo PNG:</span></span>
<span id="cb7-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#ggsave("acw_135.png", width=10, height = 10, dpi = 1000, units = "in")</span></span></code></pre></div>
</div>
<p>El resultado de todo lo anterior es una visualización de la evolución de nuestro ACW bajo la regla 135:</p>
<p><a href="acw_135.png" class="lightbox" data-gallery="quarto-lightbox-gallery-1"><img src="https://alejandroromerog.github.io/blog/ACW/acw_135.png" class="img-fluid"></a></p>
</section>
<section id="explorando-el-espacio-de-reglas" class="level2">
<h2 class="anchored" data-anchor-id="explorando-el-espacio-de-reglas">Explorando el Espacio de Reglas</h2>
<p>Ya que hemos visto cómo funciona un ACW bajo una regla específica, podemos explorar cómo cambia el comportamiento de nuestro sistema cuando cambiamos la regla. Para ello, a continuación y gracias a <a href="https://github.com/coatless/quarto-webr"><code>quarto-webr</code></a>, podemos modificar y correr el siguiente chunk de código para explorar el espacio de reglas (0 a 255): solamente debemos cambiar el número de la regla dentro de la función <code>ACW</code> y darle clic a <em>Run Code:</em></p>
<div id="qwebr-insertion-location-1"></div>
<noscript>Please enable JavaScript to experience the dynamic code cell content on this page.</noscript>
<div id="qwebr-insertion-location-2"></div>
<noscript>Please enable JavaScript to experience the dynamic code cell content on this page.</noscript>
</section>
<section id="conclusión-y-reflexiones" class="level2">
<h2 class="anchored" data-anchor-id="conclusión-y-reflexiones">Conclusión y Reflexiones</h2>
<p>Al concluir este viaje a través de los ACW en R, hemos explorado no solo un fascinante modelo matemático, sino también la profunda complejidad que puede surgir de reglas aparentemente simples. Los ACW nos ofrecen una ventana única hacia la naturaleza emergente de los sistemas complejos, un concepto que encuentra resonancia en campos tan variados como la biología, la informática, la física e incluso la economía, la sociología y demás ciencias sociales.</p>
<section id="lecciones-aprendidas" class="level3">
<h3 class="anchored" data-anchor-id="lecciones-aprendidas">Lecciones Aprendidas</h3>
<ul>
<li>Simplicidad y Complejidad: Hemos visto cómo estructuras simples pueden dar lugar a patrones increíblemente complejos y variados. Esta es una poderosa metáfora de cómo sistemas simples pueden generar fenómenos emergentes en el mundo real. Por ejemplo, la complejidad de un individuo surge de la interacción y coevolución con otros individuos, su entorno socioeconómico-cultural y factores psicológicos y biológicos.</li>
<li>Exploración y Experimentación: La capacidad de experimentar con diferentes reglas y configuraciones nos recuerda la importancia de la exploración en la ciencia y la tecnología. Cada cambio en la regla puede revelar nuevos patrones y comportamientos, alentando una mentalidad de descubrimiento continuo. Además, logramos aprender cómo graficar celdas producto de una simulación, lo cual es una habilidad útil para trabajar con datos en general.</li>
</ul>
</section>
<section id="referencias-e-inspiración" class="level3">
<h3 class="anchored" data-anchor-id="referencias-e-inspiración">Referencias e Inspiración</h3>
<p>Este artículo se basa en el trabajo de tres personas. Primero, el físico <a href="https://en.wikipedia.org/wiki/Stephen_Wolfram">Stephen Wolfram</a>, quien en 2002 publicó un libro titulado <a href="https://www.wolframscience.com/nks/">A New Kind of Science</a> (Un Nuevo Tipo de Ciencia), en el cual introduce y explora los ACW y sus implicaciones en la ciencia y la tecnología. En segundo lugar, el economista y científico de la complejidad <a href="https://scholar.google.com/citations?user=AbyywUEAAAAJ&amp;hl=es">Gonzalo Castañeda</a>, quien en 2021 publicó <a href="https://ceey.org.mx/the-paradigm-of-social-complexity/">The Paradigm of Social Complexity</a> (El Paradigma de la Complejidad Social): un libro que, en dos volúmenes, construye un marco teórico y práctico para el estudio de fenómenos socioeconómicos a través de conceptos como los Sistemas Adaptables Complejos, Autómatas Celulares y Modelos Basados en Agentes. Finalmente, al maestro <a href="https://en.wikipedia.org/wiki/Daniel_Shiffman">Daniel Shiffman</a>, quien con su canal de Youtube <a href="https://www.youtube.com/@TheCodingTrain">The Coding Train</a> y su libro <a href="https://natureofcode.com/">The Nature of Code</a> (La Naturaleza del Código) me inspiró y ayudó a implementar este proyecto en R.</p>
<p>Espero sinceramente que hayas encontrado tanto valor como inspiración en el fascinante mundo de los Autómatas Celulares de Wolfram. Mi objetivo al compartir esta exploración en R no es solo presentar un tema interesante y complejo de manera accesible, sino también encender tu curiosidad y el deseo de experimentar más allá de lo que hemos explorado aquí. Animo a cada uno de ustedes a tomar lo que hemos aprendido y expandirlo, ya sea creando nuevas versiones, aplicando estos conceptos en diferentes contextos o explorando nuevas áreas que aún estén por descubrir. La belleza de la programación y la ciencia de datos radica en su naturaleza exploratoria, en cómo nos permite dar forma a nuestras ideas y teorías.</p>


</section>
</section>

 ]]></description>
  <category>R</category>
  <category>Tutorial</category>
  <category>Visualización</category>
  <category>Autómatas Celulares</category>
  <guid>https://alejandroromerog.github.io/blog/ACW/</guid>
  <pubDate>Tue, 23 Jan 2024 06:00:00 GMT</pubDate>
  <media:content url="https://alejandroromerog.github.io/blog/ACW/acw_135_rect.png" medium="image" type="image/png" height="70" width="144"/>
</item>
<item>
  <title>Presentaciones desde RStudio con {xaringan}</title>
  <link>https://alejandroromerog.github.io/blog/xaringan/</link>
  <description><![CDATA[ 





<p>Primero, necesitamos instalar y cargar los paquetes necesarios:</p>
<div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">install.packages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pagedown"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"xaringan"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dependencies =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(pagedown)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(xaringan)</span></code></pre></div>
<p>Ahora, para generar nuestra primer presentación, pondremos la siguiente estructura en un archivo .Rmd vacío:</p>
<div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb2-2">title<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Práctica 1"</span></span>
<span id="cb2-3">subtitle<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Presentación hecha con {xaringan}"</span></span>
<span id="cb2-4">author<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alejandro Romero González"</span></span>
<span id="cb2-5">date<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10/25/2021"</span></span>
<span id="cb2-6">output<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb2-7">    xaringan<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span>moon_reader<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb2-8">      css<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>]</span>
<span id="cb2-9">      nature<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb2-10">        highlightStyle<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> github</span>
<span id="cb2-11">        highlighLine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> true</span>
<span id="cb2-12">        countIncrementalSlides<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> true</span>
<span id="cb2-13"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span></code></pre></div>
<p>Al guardar dicho archivo y después darle clic a <em>Knit</em>, RStudio compilará un html con el siguiente contenido:</p>
<p><a href="uno.png" class="lightbox" data-gallery="quarto-lightbox-gallery-1"><img src="https://alejandroromerog.github.io/blog/xaringan/uno.png" class="img-fluid"></a></p>
<p>Podrás ver que la presentación está un poco fea. Para darle un mejor estilo podemos <a href="https://cran.r-project.org/web/packages/xaringanthemer/vignettes/xaringanthemer.html">crear nuestro propio tema</a> o utilizar los temas precargados. Estos últimos podemos visualizarlos escribiendo lo siguiente en la consola:</p>
<div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(xaringan<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list_css</span>())</span></code></pre></div>
<p>Yo escogeré la fuente “tamu-fonts” y el tema “shinobi”. Se aplican en el .Rmd de la siguiente manera:</p>
<div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb4-2">title<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Práctica 1"</span></span>
<span id="cb4-3">subtitle<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Presentación hecha con {xaringan}"</span></span>
<span id="cb4-4">author<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alejandro Romero González"</span></span>
<span id="cb4-5">date<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10/25/2021"</span></span>
<span id="cb4-6">output<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb4-7">    xaringan<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span>moon_reader<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb4-8">      css<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tamu-fonts"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shinobi"</span>]</span>
<span id="cb4-9">      nature<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb4-10">        highlightStyle<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> github</span>
<span id="cb4-11">        highlighLine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> true</span>
<span id="cb4-12">        countIncrementalSlides<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> true</span>
<span id="cb4-13"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span></code></pre></div>
<p>Guardamos y compilamos de nuevo. El <strong><em>output</em></strong> ahora es este:</p>
<p><a href="dos.png" class="lightbox" data-gallery="quarto-lightbox-gallery-2"><img src="https://alejandroromerog.github.io/blog/xaringan/dos.png" class="img-fluid"></a></p>
<p>Ya se ve mejor. Sin embargo, está algo tedioso que una ventana adicional aparezca para poder visualizar la presentación. Es por ello que existe <em>Infinite Moon Reader</em>: éste <em>addin</em> nos permitirá visualizar la presentación en el <em>viewer</em> que está integrado a RStudio (como cuando visualizamos gráficas de <code>{ggplot2}</code>). Para activarlo solo es necesario darle clic al botón <em>Addins</em> que se encuentra en la parte superior de RStudio, buscar <em>Infinite Moon Reader</em> y oprimir clic de nuevo (si saltan avisos de que necesitamos instalar o actualizar algunos paquetes, les damos aceptar). Con esto, ya podremos visualizar la presentación desde Rstudio actualizándose en tiempo real (la mayor parte de las veces).</p>
<div class="callout callout-style-default callout-tip callout-titled" title="Nota">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Nota
</div>
</div>
<div class="callout-body-container callout-body">
<p>Si <em>Infinite Moon Reader</em> no aparece en <em>Addins</em>, reinstalen el paquete <code>{xaringan}</code>, pero ahora desde la repo oficial en Github:</p>
<div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">remotes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">install_github</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"yihui/xaringan"</span>)</span></code></pre></div>
</div>
</div>
<p>Para crear nuevas diapositivas simplemente tenemos que escribir debajo del área donde definimos el título, subtítulo, etc., e ir separando diapositiva por diapositiva con tres guiones. Ejemplo:</p>
<div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb6-2">title<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Práctica 1"</span></span>
<span id="cb6-3">subtitle<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Presentación hecha con {xaringan}"</span></span>
<span id="cb6-4">author<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alejandro Romero González"</span></span>
<span id="cb6-5">date<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10/25/2021"</span></span>
<span id="cb6-6">output<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb6-7">    xaringan<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span>moon_reader<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb6-8">      css<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tamu-fonts"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shinobi"</span>]</span>
<span id="cb6-9">      nature<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb6-10">        highlightStyle<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> github</span>
<span id="cb6-11">        highlighLine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> true</span>
<span id="cb6-12">        countIncrementalSlides<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> true</span>
<span id="cb6-13"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb6-14"></span>
<span id="cb6-15">class<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> inverse</span>
<span id="cb6-16"></span>
<span id="cb6-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Mi primera diapositiva</span></span>
<span id="cb6-18"></span>
<span id="cb6-19">Esto es un texto</span>
<span id="cb6-20">  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Elemento <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb6-21">  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Elemento <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb6-22">  </span>
<span id="cb6-23">  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.</span> Uno</span>
<span id="cb6-24">  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.</span> Dos</span>
<span id="cb6-25">  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.</span> Tres</span>
<span id="cb6-26">  </span>
<span id="cb6-27"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb6-28"></span>
<span id="cb6-29"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Mi segunda diapositiva</span></span>
<span id="cb6-30"></span>
<span id="cb6-31">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">in</span> reprehenderit <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">in</span> voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt <span class="cf" style="color: #003B4F;
background-color: null;
font-style: inherit;">in</span> culpa qui officia deserunt mollit anim id est laborum.</span></code></pre></div>
<p><strong><em>Output</em></strong>:</p>
<div style="display: flex; justify-content: center; align-items: center;">
    <img src="https://alejandroromerog.github.io/blog/xaringan/tres.png" style="max-width: 55%; height: auto; padding: 0px;">
    <img src="https://alejandroromerog.github.io/blog/xaringan/cuatro.png" style="max-width: 55%; height: auto; padding: 0px;">
</div>
<div class="callout callout-style-default callout-tip callout-titled" title="Nota">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Nota
</div>
</div>
<div class="callout-body-container callout-body">
<p>El color de fondo predeterminado del tema que escogí es el blanco, sin embargo lo cambié al color inverso con “class: inverse”, como se puede ver en el código de arriba.</p>
</div>
</div>
<p>Para poner links a una página web dentro de una diapositiva podemos hacerlo de tres maneras:</p>
<div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb7-2"></span>
<span id="cb7-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Diapositiva con links</span></span>
<span id="cb7-4"></span>
<span id="cb7-5"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Simplemente poner el link<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> https<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">//</span>cran.r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>project.org<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb7-6"></span>
<span id="cb7-7"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Usar sintaxis de Rmarkdown<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [link a CRAN](https<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">//</span>cran.r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>project.org<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>)</span>
<span id="cb7-8"></span>
<span id="cb7-9"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb7-10"></span>
<span id="cb7-11"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Usar sintaxis de HTML</span>
<span id="cb7-12"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>a href<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://cran.r-project.org/"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb7-13">  Link a CRAN con a href</span>
<span id="cb7-14"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">/</span>a<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div>
<p><strong><em>Output</em></strong>:</p>
<p><a href="cinco.png" class="lightbox" data-gallery="quarto-lightbox-gallery-3"><img src="https://alejandroromerog.github.io/blog/xaringan/cinco.png" class="img-fluid"></a></p>
<p>Si queremos insertar código y gráficas de R simplemente tenemos que insertar un nuevo code chunk y escribir nuestras instrucciones:</p>
<div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb8-2"></span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Diapositiva con código y gráficas de R</span></span>
<span id="cb8-4"></span>
<span id="cb8-5">\<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">```</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">{r, out.width = "300px"}</span></span>
<span id="cb8-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">library(ggplot2)</span></span>
<span id="cb8-7"></span>
<span id="cb8-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ggplot(mpg) +</span></span>
<span id="cb8-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    aes(cty, hwy) +</span></span>
<span id="cb8-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    geom_point() +</span></span>
<span id="cb8-11"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    ggtitle("Fuel efficiency!")</span></span>
<span id="cb8-12"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div>
<div class="callout callout-style-default callout-tip callout-titled" title="Nota">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Nota
</div>
</div>
<div class="callout-body-container callout-body">
<p>En el bloque de código anterior, hemos utilizado un método especial para “escapar” el bloque de código interno de RMarkdown. Esto significa que hemos añadido barras invertidas (“\”) antes de las comillas invertidas que normalmente delimitan un bloque de código. Hacemos esto para que el bloque interno se muestre como un ejemplo de código en el documento, pero sin que se ejecute realmente como código R.</p>
</div>
</div>
<p><strong><em>Output</em></strong>:</p>
<p><a href="seis.png" class="lightbox" data-gallery="quarto-lightbox-gallery-4"><img src="https://alejandroromerog.github.io/blog/xaringan/seis.png" class="img-fluid"></a></p>
<p>También podemos insertar imágenes (incluso pueden ser <em>gifs</em>) de dos maneras, estilo RMarkdown o estilo HTML:</p>
<div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb9-2"></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Diapositiva con imágenes</span></span>
<span id="cb9-4"></span>
<span id="cb9-5"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Estilo Rmarkdown<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb9-6"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>[Este es Tobías](Imagenes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>tobi.png)</span>
<span id="cb9-7"></span>
<span id="cb9-8"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb9-9"></span>
<span id="cb9-10"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Estilo HTML<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb9-11"></span>
<span id="cb9-12"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>div align<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"center"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb9-13"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>img src<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Imagenes/tobi.png"</span> width<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"650"</span> height<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"500"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb9-14"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb9-15"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb9-16">Este es Tobías</span>
<span id="cb9-17"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">/</span>div<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div>
<p><strong><em>Output</em></strong>:</p>
<div style="display: flex; justify-content: center; align-items: center;">
    <img src="https://alejandroromerog.github.io/blog/xaringan/siete.png" style="max-width: 55%; height: auto; padding: 0px;">
    <img src="https://alejandroromerog.github.io/blog/xaringan/ocho.png" style="max-width: 55%; height: auto; padding: 0px;">
</div>
<div class="callout callout-style-default callout-tip callout-titled" title="Nota">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Nota
</div>
</div>
<div class="callout-body-container callout-body">
<p>Preferiblemente hay que usar el estilo HTML debido a que no podemos cambiar el tamaño de la imagen de otro modo.</p>
</div>
</div>
<p>La imagen que inserté anteriormente estaba guardada en la memoria de mi computadora. Sin embargo, también podemos introducir imágenes que se encuentren en internet:</p>
<div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb10-2"></span>
<span id="cb10-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Imagen desde internet</span></span>
<span id="cb10-4"></span>
<span id="cb10-5"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb10-6"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>div align<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"center"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb10-7"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>img src<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://media.giphy.com/media/Ihf1VjXyflOU6Mhh3l/giphy-downsized-large.gif"</span> width<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"700"</span> height<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"400"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb10-8"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb10-9"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb10-10">Fractal de Mandelbrot</span>
<span id="cb10-11"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">/</span>div<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div>
<p><strong><em>Output</em></strong>:</p>
<p><a href="nueve.png" class="lightbox" data-gallery="quarto-lightbox-gallery-5"><img src="https://alejandroromerog.github.io/blog/xaringan/nueve.png" class="img-fluid"></a></p>
<p>También podemos dividir cada diapositiva en dos partes e insertar ecuaciones LaTeX de la siguiente manera:</p>
<div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">---</span></span>
<span id="cb11-2"></span>
<span id="cb11-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dividir la diapositiva en dos y agregar fórmulas en LaTeX</span></span>
<span id="cb11-4"></span>
<span id="cb11-5">.pull<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>left[</span>
<span id="cb11-6"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb11-7"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>div align<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"center"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb11-8"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>img src<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://media.giphy.com/media/PkKzNQjwPy7GvxZbfe/giphy.gif"</span> width<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"300"</span> height<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"300"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb11-9"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb11-10">Agujero negro</span>
<span id="cb11-11"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">/</span>div<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb11-12"></span>
<span id="cb11-13">]</span>
<span id="cb11-14"></span>
<span id="cb11-15">.pull<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>right[</span>
<span id="cb11-16"><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">&lt;</span>br<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb11-17">Fórmula para hallar la temperatura de un agujero negro<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb11-18"></span>
<span id="cb11-19"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">$$</span>T <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> \frac{\hbar c<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>}{<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>\pi kGM}<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span></span></code></pre></div>
<p><strong><em>Output</em></strong>:</p>
<p><a href="diez.png" class="lightbox" data-gallery="quarto-lightbox-gallery-6"><img src="https://alejandroromerog.github.io/blog/xaringan/diez.png" class="img-fluid"></a></p>
<p><strong><em>¡Fin!</em></strong></p>
<p><a href="once.png" class="lightbox" data-gallery="quarto-lightbox-gallery-7"><img src="https://alejandroromerog.github.io/blog/xaringan/once.png" class="img-fluid"></a></p>
<div class="callout callout-style-default callout-tip callout-titled" title="Notas adicionales">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Notas adicionales
</div>
</div>
<div class="callout-body-container callout-body">
<p>Si quieres subir tu presentación a internet, te recomiendo seguir este otro tutorial: <a href="https://silviacanelon.com/blog/2021-03-16-deploying-xaringan-slides/">https://silviacanelon.com/blog/2021-03-16-deploying-xaringan-slides/</a>.</p>
<p>El link de la presentación que cree en el presente tutorial es el siguiente: <a href="https://alejandroromerog.github.io/PracticaUnoXaringan/#1">https://alejandroromerog.github.io/PracticaUnoXaringan/#1</a>.</p>
</div>
</div>



 ]]></description>
  <category>R</category>
  <category>Tutorial</category>
  <guid>https://alejandroromerog.github.io/blog/xaringan/</guid>
  <pubDate>Tue, 14 Nov 2023 06:00:00 GMT</pubDate>
  <media:content url="https://alejandroromerog.github.io/blog/xaringan/xaringan.png" medium="image" type="image/png" height="76" width="144"/>
</item>
</channel>
</rss>
