---
title: "Introduction to censobr"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
code-annotations: hover
urlcolor: blue
vignette: >
  %\VignetteIndexEntry{Introduction to censobr}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = identical(tolower(Sys.getenv("NOT_CRAN")), "true"),
  out.width = "100%"
)

```

**{censobr}** is an R package to download data from Brazil's Population Census. It provides a very simple and efficient way to download and read the data sets and documentation of all the population censuses taken in and after 1960 in the country. The **{censobr}** package is built on top of the [Arrow platform](https://arrow.apache.org/docs/r/), which allows users to work with larger-than-memory census data using [{dplyr} familiar functions](https://arrow.apache.org/docs/r/articles/arrow.html#analyzing-arrow-data-with-dplyr).

# Installation

```R
# install from CRAN
install.packages("censobr")

# or use the development version with latest features
utils::remove.packages('censobr')
remotes::install_github("ipeaGIT/censobr", ref="dev")

```


# Basic usage

The package currently includes 6 main functions to download census data:

1. `read_population()`
2. `read_households()`
3. `read_mortality()`
4. `read_families()`
5. `read_emigration()`
6. `read_tracts()`

<table cellpadding="0" cellspacing="0" style="border-collapse:collapse" border="1">
  <thead>
    <tr>
      <th rowspan="2"><center>Função</center></th>
      <th rowspan="2"><center>Origem</center></th>
      <th rowspan="2"><center>Unidade</center></th>
      <th rowspan="2"><center>Definição</center></th>
      <th colspan="7"><center>Disponibilidade</center></th>
    </tr>
    <tr>
      <th>1960</th>
      <th>70</th>
      <th>80</th>
      <th>91</th>
      <th>2000</th>
      <th>10</th>
      <th>22</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>read_population()</td>
      <td>Amostra</td>
      <td>Microdado</td>
      <td>Lê os microdados de pessoas.</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td><i>em breve</i></td>
    </tr>
    <tr>
      <td>read_households()</td>
      <td>Amostra</td>
      <td>Microdado</td>
      <td>Lê os microdados de domicílios.</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td><i>em breve</i></td>
    </tr>
    <tr>
      <td>read_families()</td>
      <td>Amostra</td>
      <td>Microdado</td>
      <td>Lê os microdados de famílias do censo de 2000.</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>read_emigration()</td>
      <td>Amostra</td>
      <td>Microdado</td>
      <td>Lê os microdados de emigração.</td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
      <td></td>
      <td><i>em breve</i></td>
    </tr>
    <tr>
      <td>read_mortality()</td>
      <td>Amostra</td>
      <td>Microdado</td>
      <td>Lê os microdados de mortalidade.</td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
      <td><i>em breve</i></td>
    </tr>
    <tr>
      <td>read_tracts()</td>
      <td>Universo</td>
      <td>Setor Censitário</td>
      <td>Lê os dados do Universo agregados por setores censitários.</td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td><i>em breve</i></td>
      <td>X</td>
      <td><i>em breve</i></td>
    </tr>
  </tbody>
</table>


**{censobr}** also includes a few support functions to help users navigate the documentation Brazilian censuses, providing convenient information on data variables and methodology.:

7. `data_dictionary()`
8. `questionnaire()`
9. `interview_manual()`


Finally, the package includes a function to help users to manage the data cached locally.

10. `censobr_cache()` 

The syntax of all **{censobr}** functions to read data operate on the same logic so it becomes intuitive to download any data set using a single line of code. Like this:

```{r, eval = FALSE}
read_households(
  year,          # year of reference
  columns,       # select columns to read
  add_labels,    # add labels to categorical variables
  as_data_frame, # return an Arrow DataSet or a data.frame
  showProgress,  # show download progress bar
  cache          # cache data for faster access later
  )
```

***Note:*** all data sets in **{censobr}** are enriched with geography columns following the name standards of the [{geobr} package](https://github.com/ipeaGIT/geobr/) to help data manipulation and integration with spatial data from {geobr}. The added columns are: `c(‘code_muni’, ‘code_state’, ‘abbrev_state’, ‘name_state’, ‘code_region’, ‘name_region’, ‘code_weighting’)`.

***Data Cache:***

The first time the user runs a function, **{censobr}** will download the file and store it locally. This way, the data only needs to be downloaded once. More info in the [Data cache section](https://ipeagit.github.io/censobr/articles/censobr.html#data-cache) below.


# Larger-than-memory Data

Data of Brazilian censuses are often too big to load in users' RAM memory. To avoid this problem, **{censobr}** will by default return an [Arrow table](https://arrow.apache.org/docs/r/articles/arrow.html#tabular-data-in-arrow), which can be analyzed like a regular `data.frame` using the `dplyr` package without loading the full data to memory.

Let's see how **{censobr}** works in a couple examples:

# Reproducible examples

First, let's load the libraries we'll be using in this vignette.

```{r warning=FALSE, message=FALSE}
library(censobr)
library(arrow)
library(dplyr)
library(ggplot2)
```

### Using Population data:

In this example we'll be calculating the proportion of people with higher education in different racial groups in the state of Rio de Janeiro. First, we need to use the `read_population()` function to download the population data set.

Since we don't need to load to memory all columns from the data, we can pass a vector with the names of the columns we're going to use. This might be necessary in more constrained computing environments. Note that by setting `add_labels = 'pt'`, the function returns labeled values for categorical variables.

```{r warning = FALSE, message=FALSE}
pop <- read_population(year = 2010,
                       columns = c('abbrev_state', 'V0606', 'V0010', 'V6400'),
                       add_labels = 'pt',
                       showProgress = FALSE)

class(pop)
```
By default, the output of the function is an `"arrow_dplyr_query"`. This is makes it possible for you to work with the census data in a super fast and efficient way, even though the data set might be to big for your computer memory. By setting the parameter `as_data_frame = TRUE`, the read functions load the entire output to memory as a `data.frame`. *Warning:* This can cause the R session to crash in computationally constrained environments.

The output of the read functions in **{censobr}** can be analyzed like a regular `data.frame` using the `{dplyr}` package. For example, one can have a quick peak into the data set with `glimpse()`

```{r warning = FALSE, message=FALSE}
dplyr::glimpse(pop)
```


In the example below, we use the `dplyr` syntax to (a) filter observations for the state of Rio de Janeiro, (b) group observations by racial group, (c) summarize the data calculating the proportion of individuals with higher education. Note that we need to add a `collect()` call at the end of our query.

```{r warning = FALSE, message=FALSE}
df <- pop |>
      filter(abbrev_state == "RJ") |>                                                    # (a)
      compute() |>
      group_by(V0606) |>                                                                 # (b)
      summarize(higher_edu = sum(V0010[which(V6400=="Superior completo")]) / sum(V0010), # (c)
                pop = sum(V0010) ) |>
      collect()

head(df)
```
Now we only need to plot the results.

```{r, message=FALSE}
df <- subset(df, V0606 != 'Ignorado')

ggplot() +
  geom_col(data = df, aes(x=V0606, y=higher_edu), fill = '#5c997e') +
  scale_y_continuous(name = 'Proportion with higher education',
                     labels = scales::percent) +
  labs(x = 'Cor/raça') +
  theme_classic()
  
```

### Using household data:

#### Sewage coverage:

In this example, we are going to map the proportion of households connected to a sewage network in Brazilian municipalities First, we can easily download the households data set with the `read_households()` function.

```{r, message=FALSE}
hs <- read_households(year = 2010, 
                      showProgress = FALSE)

```

Now we're going to (a) group observations by municipality, (b) get the number of households connected to a sewage network, (c) calculate the proportion of households connected, and (d) collect the results.

```{r warning = FALSE, message=FALSE}
esg <- hs |> 
        compute() |>
        group_by(code_muni) |>                                             # (a)
        summarize(rede = sum(V0010[which(V0207=='1')]),                    # (b)
                  total = sum(V0010)) |>                                   # (b)
        mutate(cobertura = rede / total) |>                                # (c)
        collect()                                                          # (d)

head(esg)
```
In order to create a map with these values, we are going to use the [{geobr} package](https://ipeagit.github.io/geobr/) to download the geometries of Brazilian municipalities.

```{r warning = FALSE, message=FALSE}
library(geobr)

muni_sf <- geobr::read_municipality(year = 2010,
                                    showProgress = FALSE)
head(muni_sf)
```

Now we only need to merge the spatial data with our estimates and map the results.

```{r warning = FALSE, message=FALSE}
esg_sf <- left_join(muni_sf, esg, by = 'code_muni')

ggplot() +
  geom_sf(data = esg_sf, aes(fill = cobertura), color=NA) +
  labs(title = "Share of households connected to a sewage network") +
  scale_fill_distiller(palette = "Greens", direction = 1, 
                       name='Share of\nhouseholds', 
                       labels = scales::percent) +
  theme_void()

```

#### Spatial distribution of rents:

In this final example, we're going to visualize how the amount of money people spend on rent varies spatially across the metropolitan area of São Paulo.

First, let's download the municipalities of the metro area of São Paulo.
```{r warning = FALSE, message=FALSE}
metro_muni <- geobr::read_metro_area(year = 2010, 
                                     showProgress = FALSE) |> 
              subset(name_metro == "RM São Paulo")
```
We also need the polygons of the weighting areas (áreas de ponderação). With the code below, we download all weighting areas in the state of São Paulo, and then keep only the ones in the metropolitan region of São Paulo.

```{r warning = FALSE, message=FALSE}
wt_areas <- geobr::read_weighting_area(code_weighting = "SP", 
                                       showProgress = FALSE,
                                       year = 2010)

wt_areas <- subset(wt_areas, code_muni %in% metro_muni$code_muni)
head(wt_areas)
```


Now we need to calculate the average rent spent in each weighting area. Using the national household data set, we're going to (a) filter only observations in our municipalities of interest, (b) group observations by weighting area, (c) calculate the average rent, and (d) collect the results.

```{r warning = FALSE, message=FALSE}
rent <- hs |>
        filter(code_muni %in% metro_muni$code_muni) |>                     # (a)
        compute() |>
        group_by(code_weighting) |>                                        # (b)
        summarize(avgrent=weighted.mean(x=V2011, w=V0010, na.rm=TRUE)) |>  # (c)
        collect()                                                          # (d)

head(rent)
```
Finally, we can merge the spatial data with our rent estimates and map the results.

```{r warning = FALSE, message=FALSE}
rent_sf <- left_join(wt_areas, rent, by = 'code_weighting')

ggplot() +
  geom_sf(data = rent_sf, aes(fill = avgrent), color=NA) +
  geom_sf(data = metro_muni, color='gray', fill=NA) +
  scale_fill_distiller(palette = "Greens", direction = 1, 
                       name='Avgerage\nRent in R$') +
  theme_void()

```



## Data cache

The first time the user runs a function, **{censobr}** will download the file and store it locally. This way, the data only needs to be downloaded once. When the `cache` parameter is set to `TRUE` (Default), the function will read the cached data, which is much faster. 

Users can manage the cached data sets using the `censobr_cache()` function. For example, users can:

List cached files:
```{r warning=FALSE, eval=FALSE}
censobr_cache(list_files = TRUE)
```

Delete a particular file:
```{r warning=FALSE, eval=FALSE}
censobr_cache(delete_file = "2010_emigration")

```

Delete all files:
```{r warning=FALSE, eval=FALSE}
censobr_cache(delete_file = "all")

```

By default, **{censobr}** files are saved in the 'User' directory. However, users can run the function `set_censobr_cache_dir()` to set custom cache directory.

```{r, eval=FALSE, warning=FALSE}
tempf <- tempdir()

set_censobr_cache_dir(path = tempf)

```



