---
title: "A journey into *mapping*"
output: 
  rmarkdown::html_vignette:
    keep_md: true 
    toc: true
vignette: >
  %\VignetteIndexEntry{A journey into mapping}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, collapse = TRUE, 
                      fig.width = 7, fig.height = 4,
                      fig.align = "center", message = FALSE, warning = FALSE)

```



**mapping** allows to easily show data using maps, automatically link spatial coordinates to data, and transform data with spatial coordinates.
The mapping functions use the already available and well implemented function in tmap, cartography, and leaflet packages.


Given the differnt boundary structure of each country, the package provide specific mapping functions and building object functions to link e manipulate data with spatial coordinates.

| Country | Object creation function |Object Class |  Map Function|
------------|------------| ------------ | ------------ | -------
| World |  `WR()` | **WR** | `mappingWR()` | 
| European population for nuts 2| `EU()`| **EU** | `mappingEU()`|
| European population for nuts 3  | `IT()` | **IT** | `mappingIT()` |
| Italian population | `US()`| **US** | `mappingUS()`|


The CRAN version can be loaded as follows:
```{r, message = FALSE}
library('mapping')
```

or the development version from GitHub:

```{r, message = FALSE, eval=FALSE}
remotes::install_github('dataallaround/mapping')
```


## Datasets 

| Description | Dataset name |
------------|------------|
| World population |  `WR()` | 
| European population nuts 2| `EU()`| 
| Italy | `IT()` 
| USA 208-2016 election results | `US()`| 
| Tax wedge OCDE countries 2018 |   |


```{r}
data("popWR")
str(popWR)
```

```{r}
data("popEU")
str(popEU)
```

```{r}
data("popIT")
str(popIT)
```
```{r}
data("popUS")
str(popUS)
```

## Load coordinates and check names


Coordinates can be separately downloaded using this specific functions


| Coordinates | Function| 
------------|------------|
| World | `loadCoordWR()` |
| European Union| `loadCoordEU()`|
| Italy | `loadCoordIT()` |
| United States of America | `loadCoordUS()`|

Coordinates are download from the GitHub repository \url{https://github.com/dataallaround/geospatial}, which provides .geojson and .RData files with coordinates, which return an object of class `sf`.

```{r}
coord_eu <- loadCoordEU(unit = "nuts0")
```

The `unit` argument in the `load` functions, indicates the type of statistical unit, geographical subdivision or level of aggregation.

```{r}
library(tmap)
tm_shape(coord_eu) + tm_borders()
```

Returning an object of class `sf`, we can also use the mapping function available in the other R packages. 

Note that, the data are downloaded from an online repository, and then an internet connection should be preferred. Nevertheless, if the `use_internet` argument set to `FALSE`, we will get the coordinates locally available in the package.

`checkNames` functions will return the nomatching names:

```{r, eval=FALSE}
checkNamesIT(popIT$ID, unit = "provincia")
```


`GetNames` functions returns the names used in the packages for each `unit`.

```{r}
head(getNamesEU(unit = "nuts0"))
head(getNamesEU(unit = "nuts0", all_levels = FALSE))
```


## Building a **mapping** object


The `popIT`, as showed in the previous section, does not contain any information about the geographical geometries:

```{r}
str(popIT)
```

then, the coordinates are added as follows:

```{r}
it <- IT(data = popIT, unit = "provincia", year = "2018",colID = "ID")
```


We have to specify the type of statistical unit, the column containing the ids and, if necessary, the year of the subdivision, and the functions will automatically download the coordinates and link them to the data.

```{r}
str(it,1)
```

In linking the data and the coordinates, the functions available in this packages will return also the information about larger units

```{r}
library(tmap)
tm_shape(it) + tm_borders() + tm_fill("totale")
```


Data can be subsets before mapping

```{r}
it <- IT(data = popIT, unit = "provincia", 
         year = "2018",colID = "ID",
         subset = ~ I(regione == "Lazio"))
```


```{r}
tm_shape(it) + tm_borders()
```

and add variables

```{r}
it <- IT(data = popIT, unit = "provincia", 
         year = "2018",colID = "ID",
         add = ~I(maschi/totale) + I(femmine/totale), 
         new_var_names = c("Male percentage", "Female percentage"),
         print = FALSE)

str(it,1)
```

Note that, the `matchWith` argument indicates the type of names we have to link, for example code number, iso code, and so on



```{r}
str(popEU)
eu <- EU(data = popEU, unit = "nuts0", colID = "GEO", 
         matchWith = "id", check.unit.names = FALSE)
```


## Static maps


```{r}
coord_eu <- loadCoordEU(unit = "nuts0")
mappingEU(data = coord_eu)
```


Now we look at the distribution of population among European countries



```{r}
eu <- EU(data = popEU, unit = "nuts0", colID = "GEO", 
         matchWith = "iso2", check.unit.names = FALSE)
mappingEU(eu, var = "total")
```

matching with iso2 code.

It is equivalent to use mapping function without building as `EU` object 

```{r}
mappingEU(data = popEU,unit = "nuts0", colID = "GEO", matchWith = "iso2", var = "total")
```

The `loadCoord` functions, as explained in the previous section, automatically return all the bigger statistical unit aggregation starting from the input `unit`.



```{r}
eu_aggr <- EU(data = popEU, unit = "nuts1", colID = "GEO", 
         matchWith = "id", check.unit.names = FALSE,
         aggregation_var = "total", aggregation_unit = "nuts0", aggregation_fun = sum)

mappingEU(eu_aggr, var = "total")
```

or the same as follows

```{r}
eu <- EU(data = popEU, unit = "nuts1", colID = "GEO", 
         matchWith = "id", check.unit.names = FALSE)


mappingEU(eu, var = "total", aggregation_unit = "nuts0", aggregation_fun = sum)
```


We can also provide multiple variables to generate multiple maps

```{r}
mappingEU(eu, var = c("male","female"))
```


or a subset 

```{r}
mappingEU(eu, var = "total", 
          subset = ~I(country == "Spain" | country == "Italy"))
```


Let's look at USA example.


```{r}
data("popUS")
us <- US(data = popUS, unit = "state", matchWith = "name")
mappingUS(us)
```


```{r}
mappingUS(us, var = "population")

mappingUS(us, var = "population", add_text = "state_id",
          options = mapping.options(nclass = 10, legend.portrait = FALSE))
```

```{r, eval=FALSE}
mappingUS(us, var = "population", options = mapping.options(nclass = 10, legend.portrait = FALSE))
```


The `facets` argument returns the small multiples. 

```{r}
mappingUS(us, var = "population", aggregation_unit = "division", facets = "division")
```

or facets for some geographical unit

```{r}
mappingUS(us, var = "population", subset = ~I(region == "Northeast"), facets = "id")
```

In this case it maps all the divisions.


## Interactive maps

The interactive map functions work as the static functions and they share the same argument.

```{r}
eu <- EU(data = popEU, unit = "nuts0", colID = "GEO", 
         matchWith = "id", check.unit.names = FALSE)
mappingEU(eu, var = "total", type = "interactive")

```

```{r, eval=FALSE}
mappingEU(eu, var = "total", type = "interactive",
                      subset = ~I(country == "Spain" | country == "Italy"))
```

or aggregating for countries ("nuts0")

```{r, eval=FALSE}
mappingEU(eu, var = "total", type = "interactive",
                      aggregation_unit = "nuts0")
```

Multiple variable will provide a single interactive map with different layers:
```{r, eval=FALSE}
mappingEU(eu, var = c("male","female"), type = "interactive")
```

and also the `facets` is implemented for interactive maps.



## A generic `mapping()` function 

The package also provide a generic function to map data, `mapping`. This accept object of class `sf`, `WR`, `EU`, `IT`, and `US`.


```{r}
library(dplyr)

data("popIT")
popIT <- popIT
coords <- loadCoordIT(unit = "provincia", year = '2019')
cr <- left_join(coords, popIT, by = c( "provincia" = "ID"))
mapping(cr)
mapping(cr, var = "maschi")
```

```{r}
library(sf)
nc = st_read(system.file("shape/nc.shp", package="sf"))
class(nc)
mapping(nc)
```


## Layout options

Aesthetic options are controlled by `mapping.options()` function. General options can be retrieved 

```{r, eval=FALSE}
mapping.options()
```

single or multiple options may be retrieved 

```{r}
mapping.options("palette.cont")
mapping.options("legend.position")
```
and we can globally change until a new R session, as follows

```{r}
mapping.options(legend.position = c("left","bottom"))
mapping.options("legend.position")
```

Options can be changed locally in `mapping` functions:

```{r}
map <- mappingEU(eu, var = "total")
map_options <- mappingEU(eu, var = "total", 
                         options = mapping.options(list(legend.position = c("left","bottom"),
                                                        title = "EU total population",
                                                        map.frame = FALSE,
                                                        col.style = "pretty")))

library(tmap)
tmap_arrange(map, map_options)
mapping.options.reset()
```

or globally outside the functions. Original options can be reseted using `mapping.options.reset()`.


## Some other plot example

```{r}
mappingIT(data = it, var = "totale")
mappingIT(data = it, var = c("maschi", "femmine"))
mappingIT(data = it, var = c("maschi", "femmine"), options = mapping.options(palette.cont = c("Greens", "Blues"), legend.position = c("left","bottom")))

mappingIT(data = it, var = "ripartizione")


```

```{r, eval=FALSE}
mappingIT(data = it, var = "totale", add_text = "code")
```


```{r, eval=FALSE}
mappingIT(data = it, var = "totale", type = "interactive")
mappingIT(data = it, var = "totale", type = "interactive",
          options = mapping.options(legend.position = c("left","bottom")))

mappingIT(data = it, var = c("maschi", "femmine"), type = "interactive", 
          options = mapping.options(interactive.control.collapse = FALSE))
mappingIT(data = it, var = c("maschi", "femmine"), type = "interactive",
          options = mapping.options(palette.cont = c("BuGn", "BuPu")))


mappingIT(data = it, var = "totale", type = "interactive", 
          options = mapping.options(col.style = "pretty"))
mappingIT(data = it, var = "totale", type = "interactive", 
          options = mapping.options(col.style = "equal"))
mappingIT(data = it, var = "totale", type = "interactive", 
          options = mapping.options(col.style = "equal", nclass = 7))

mappingIT(data = it, var = "ripartizione", type = "interactive")
mappingIT(data = it, var = "totale", type = "interactive", facets = "ripartizione")
          
```

Some other aggregation and facets examples:

```{r}
data(popIT)
it <- IT(data = popIT, unit = "provincia", year = "2018",colID = "ID")
```


```{r}

mappingIT(data = it, var = "totale", aggregation_unit = "regione")
mappingIT(data = it, var = "totale", 
          aggregation_unit = "ripartizione", 
          aggregation_fun = function(x) sum(x, na.rm = TRUE))


mappingIT(data = it, var = "totale", 
          aggregation_unit = "regione", facets = "ripartizione")
```

```{r, eval=FALSE}
mappingIT(data = it, var = "totale", 
          aggregation_unit = "ripartizione", 
          aggregation_fun = function(x) sum(x, na.rm = TRUE),
          type = "interactive")


mappingIT(data = it, var = "totale", 
          aggregation_unit = "regione", facets = "regione")

```



```{r}
data("popEU")
popEU <- popEU
euNuts2 <- EU(data = popEU, colID = "GEO",unit = "nuts2",matchWith = "id")
str(euNuts2,1)

mappingEU(data = euNuts2, var = "total", 
          aggregation_unit = "nuts0", aggregation_fun = mean)

```

```{r}
mappingEU(data = euNuts2, var = "total", 
          aggregation_unit = "nuts0", aggregation_fun = sum)
mappingEU(data = euNuts2, var = "total", subset = ~I(iso3 == "FRA"),
          aggregation_unit = "nuts1", aggregation_fun = sum, facets = "nuts1")
```


```{r, eval = FALSE}
data("popWR")
popWR <- popWR
wr <- WR(data = popWR, colID = "country_code",
         matchWith = "iso3_eh", check.unit.names = FALSE,
         res = "low")

mappingWR(data = wr, var = "total", 
          aggregation_unit = "continent", 
          aggregation_fun = function(x) sum(x, na.rm = TRUE))


mappingWR(data = wr, var = "total", 
          aggregation_unit = "continent", 
          aggregation_fun = function(x) sum(x, na.rm = TRUE),
          type = "interactive")

```


<!-- ### "choro.cart" -->

<!-- ```{r} -->
<!-- mappingIT(data = it, var = "totale", typeStatic = "choro.cart") -->
<!-- mappingIT(data = it, var = c("maschi", "femmine"), typeStatic = "choro.cart") -->
<!-- mappingIT(data = it, var = c("maschi", "femmine"), typeStatic = "choro.cart", mapping.options(palette.cont = c("Greens", "Blues"))) -->
<!-- ``` -->






