---
title: "Case study 2: Geographical variation in the relationship between range size and body size"
author: "Mihai Valcu"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Geographical variation in the relationship between range size and body size}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

## Appendix S3
Supporting information in  _Valcu, M., Dale, J., and Kempenaers, B. (2012).
rangeMapper: a platform for the study of macroecology of life-history traits.
Global Ecology and Biogeography 21, 945-951._

The example shown here is run on the wrens dataset which is part of the package.
The wrens dataset has 84 species while the case study presented in the paper
was run on 8434 bird species. Therefore both the settings and the results shown
below are not identical with the results presented in _Valcu et al 2012_.

### Project Set Up

For a step-by-step project set-up see Case study 1.

```{r}
require(rangeMapper)
breding_ranges = rgdal::readOGR(system.file(package = "rangeMapper",
     "extdata", "wrens", "vector_combined"), "wrens", verbose = FALSE)
data(wrens)
d = subset(wrens, select = c('sci_name', 'body_mass') )
con = ramp("wrens.sqlite", gridSize = 2.5, spdf = breding_ranges,
             biotab = d, ID = "sci_name",metadata = rangeTraits()['Area'],
             FUN = "median", overwrite = TRUE)
```
Convert `metadata_ranges` table to a life-history `BIO_` table.

```{r}
metadata2bio(con)
```
Merge the newly converted `metadata_ranges` to the other life-history table(s) previously saved.

```{r}
bio.merge(con, tableName = 'all_life_history')
```

###  Define New Functions

The newly defined function should take `formula` & `data` as arguments and should
return a numeric vector of length 1.
We define a simple wrapper around the `rlm` function in `MASS` package to extract
a robust regression slope for each assembladge (i.e. canvas cell).

Note that:

 * `...` in `rangeMap.save` allows for further arguments to be passed to `rlm()`

 * `try()` allows the computation to move on to the next canvas cell without stopping the entire process.

 * the function will return NA if `rlm` does not return a coefficient.

```{r}
rlm_slope = function (formula, data,...) {
    x = try(as.numeric(
        MASS::rlm(formula, data,...)$coefficients[2]), silent = TRUE)
    if(inherits(x, "try-error")) x = NA
    return(x)
    }
```

Map the Area ~ Body Mass slope using the user-defined function

```{r, warning=FALSE}
rangeMap.save(con, FUN = rlm_slope, biotab = "all_life_history",
    biotrait  = "body_mass_biotab",
    tableName = "rlm_slope_BM_rangeSize",
    formula   = scale(log(Area_metadata_ranges)) ~ scale(log(body_mass_biotab)),
                maxit = 20)
```

Additionally map the breeding range area

```{r, message=FALSE, warning=FALSE}
rangeMap.save(con, FUN = 'median', biotab = "all_life_history",
    biotrait  = "Area_metadata_ranges",
    tableName = "median_area")
```


Plot maps

```{r, message=FALSE, warning=FALSE, fig.width = 5, fig.height = 5}
m= rangeMap.fetch(con, spatial = FALSE,
        maps = c("species_richness", "median_body_mass","median_area", "rlm_slope_BM_rangeSize" ) )
plot(m, rm.outliers = TRUE)
```



