Introducción

En este instructivo, veremos cómo restructurar una base de datos de un formato “largo” a un formato “corto”. Esta manera de cambiar la forma de presentar los datos es útil para determinados propósitos.

Datos

Vamos a trabajar con los módulos 1 y 2 de la ENAHO 2019:

library(foreign)

enaho19.m1 <- read.spss("Enaho01-2019-100.sav", to.data.frame= T)

enaho19.m2 <- read.spss("Enaho01-2019-200.sav", to.data.frame=T)

Ejemplo

Vamos a usar como ejemplo una de las tablas del grupo “Cuantifica tu dato”:

PERÚ: TIPO DE CONEXIÓN DEL SERVICIO HIGIÉNICO DEL HOGAR, POR DOMINIO GEOGRÁFICO, SEGÚN SEXO DEL JEFE DEL HOGAR

Seleccionamos a los jefes de hogar y los juntamos con el módulo 1

jefes.hog <- subset(enaho19.m2, P203 == "Jefe/Jefa")

mis.vars <- c("CONGLOME", "VIVIENDA", "HOGAR", "P203", "P207")

jefes.hog <- jefes.hog[mis.vars]

mod1 <- merge(enaho19.m1, jefes.hog, by = c("CONGLOME", "VIVIENDA", "HOGAR"))

Tabla

library(reshape2)
library(dplyr)


tabla4 <- dcast(as.data.frame(xtabs(FACTOR07 ~ P111A + P207 + DOMINIO,
                                    data = mod1)),
                P207 + P111A ~ DOMINIO)
                
tabla4.t <-  tabla4 %>%
  select(-c(1)) %>%
  group_by(P111A) %>%
  summarise_all(funs(sum))

P207 <- "Total"

tabla4.t <- cbind(P207, tabla4.t)

tabla4 <- rbind(tabla4.t, tabla4)

tabla4$total <- rowSums(tabla4[, -c(1,2)])

## Tabla en porcentajes

tabla4.pct <- tabla4 %>%
  group_by(P207) %>%
  mutate_at(vars(3:11), funs(./sum(.)*100))

La tabla resultante es una tabla que tiene un formato “largo”:

head(tabla4.pct)
## Warning: `...` is not empty.
## 
## We detected these problematic arguments:
## * `needs_dots`
## 
## These dots only exist to allow future extensions and should be empty.
## Did you misspecify an argument?
## # A tibble: 6 x 11
## # Groups:   P207 [1]
##   P207  P111A `Costa Norte` `Costa Centro` `Costa Sur` `Sierra Norte`
##   <chr> <fct>         <dbl>          <dbl>       <dbl>          <dbl>
## 1 Total Red ~        76.3            81.7        83.3          39.4  
## 2 Total Red ~         0.925           1.50        2.53          2.64 
## 3 Total Letr~         3.37            3.05        2.14          7.54 
## 4 Total Pozo~         2.69            2.46        2.24         30.7  
## 5 Total Pozo~         7.70            6.24        5.15          8.10 
## 6 Total Río,~         0.413           1.16        0             0.178
## # ... with 5 more variables: `Sierra Centro` <dbl>, `Sierra Sur` <dbl>,
## #   Selva <dbl>, `Lima Metropolitana` <dbl>, total <dbl>

Podemos convertirla en un formato “corto”, por ejemplo si queremos tener una variable que sea el Dominio Geográfico para hacer un gráfico en ggplot. Para ello usamos la función melt del paquete reshape2

names(tabla4.pct)
##  [1] "P207"               "P111A"              "Costa Norte"       
##  [4] "Costa Centro"       "Costa Sur"          "Sierra Norte"      
##  [7] "Sierra Centro"      "Sierra Sur"         "Selva"             
## [10] "Lima Metropolitana" "total"
tabla4.corto <- melt(tabla4.pct, id.vars = c("P207", "P111A"),
                     variable.name = "DOMINIO",
                     value.name = "Porcentaje")

head(tabla4.corto)
##    P207                                                                P111A
## 1 Total                         Red pública de desagüe dentro de la vivienda
## 2 Total Red pública de desagüe fuera de la vivienda pero dentro del edificio
## 3 Total                                            Letrina (con tratamiento)
## 4 Total                           Pozo séptico, tanque septico o biodigestor
## 5 Total                                                   Pozo ciego o negro
## 6 Total                                        Río, acequia, canal o similar
##       DOMINIO Porcentaje
## 1 Costa Norte 76.2804406
## 2 Costa Norte  0.9248026
## 3 Costa Norte  3.3709596
## 4 Costa Norte  2.6929743
## 5 Costa Norte  7.7007720
## 6 Costa Norte  0.4129668