Please find below the R code history from your *Wallace* session.

You can reproduce your session results by running this R Markdown file in RStudio.

Each code block is called a "chunk", and you can run them either one-by-one or all at once by choosing an option in the "Run" menu at the top-right corner of the "Source" pane in RStudio.

For more detailed information see <http://rmarkdown.rstudio.com>).

### Package installation

Wallace uses the following R packages that must be installed and loaded before starting.

```{r}
library(devtools)
library(spocc)
library(maptools)
library(spThin)
library(dismo)
library(rgeos)
library(repmis)
library(maps)
library(ENMeval)
```

Wallace also includes several functions developed to help integrate different packages and some additional functionality. For this reason, it is necessary to load the file `functions.R`, The function `system.file()` finds this script, and `source()` loads it.

```{r}
source(system.file('shiny/funcs', 'functions.R', package = 'wallace'))
```

Record of analysis for *Acer rubrum*.
-------------------------------------

### Obtain Occurrence Data

The search for occurrences was limited to 304 records. Obtain occurrence records of the selected species from the gbif database.

```{r}
results <- spocc::occ(query = "Acer rubrum", from = "gbif", limit = 304, has_coords = TRUE)
results.data <- results[["gbif"]]$data[[formatSpName("Acer rubrum")]]
occs <- remDups(results.data)  # remove rows with duplicate coordinates
# make sure latitude and longitude are numeric (sometimes they aren't)
occs$latitude <- as.numeric(occs$latitude)
occs$longitude <- as.numeric(occs$longitude)
# give all records a unique ID
occs$origID <- row.names(occs)
```

Remove the occurrence localities with the following IDs: 239.

```{r}
remo <- which(occs$origID %in% '239')  # find row numbers that match IDs to be removed
occs <- occs[-remo, ]  # remove the selected rows
```

### Obtain Environmental Data

Using WorldClim (<http://www.worldclim.org/>) bioclimatic dataset at resolution of 10 arcmin.

```{r}
preds <- raster::getData(name = "worldclim", var = "bio", res = 10, lat = , lon = )
locs.vals <- raster::extract(preds[[1]], occs[, c('longitude', 'latitude')])  # extract environmental values at occ grid cells
occs <- occs[!is.na(locs.vals), ]  # remove occs without environmental values from inFile
```

### Process Environmental Data

Background selection technique chosen as Minimum Convex Polygon. Buffer size of the study extent polygon defined as 0 km.

```{r}
xy_mcp <- mcp(occs[,2:3])
bb <- xy_mcp@polygons[[1]]@Polygons[[1]]@coords
backgExt <- rgeos::gBuffer(xy_mcp, width = 0 + res(preds)[1])
```

Generate the user-defined study extent plus the buffer:

Mask environmental variables by Minimum Convex Polygon, and take a random sample of background values from the study extent. As the sample is random, your results may be different than those in the session. If there seems to be too much variability in these background samples, try increasing the number from 10,000 to something higher (e.g. 50,000 or 100,000). The better your background sample, the less variability you'll have between runs.

```{r}
predsBackgCrop <- raster::crop(preds, backgExt)
predsBackgMsk <- raster::mask(predsBackgCrop, backgExt)
occs.locs <- occs[,2:3]
bg.coords <- dismo::randomPoints(predsBackgMsk, 10000)  # generate 10,000 background points
bg.coords <- as.data.frame(bg.coords)  # get the matrix output into a data.frame
```

### Partition Occurrence Data

Here, occurrence data is partitioned for cross-validation.

Data partition by Checkerboard 2 method.

```{r}
group.data <- ENMeval::get.checkerboard2(occ=occs.locs, env=predsBackgMsk, bg.coords=bg.coords, aggregation.factor=2)
```

Define modeling parameters:

```{r}
modParams <- list(occ.pts=occs.locs, bg.pts=bg.coords, occ.grp=group.data[[1]], bg.grp=group.data[[2]])
```

### Build and Evaluate Niche Model

Maxent model selected.

```{r}
rms <- seq(1, 3, 1)  # define the vector of RMs to input
e <- ENMeval::ENMevaluate(modParams$occ.pts, predsBackgMsk, bg.coords=modParams$bg.pts, RMvalues=rms, fc='LQHPT', method='user', occ.grp=modParams$occ.grp, bg.grp=modParams$bg.grp)
evalTbl <- e@results
evalMods <- e@models
evalPreds <- e@predictions  # raw predictions

evalPredsLog <- stack(sapply(e@models, function(x) predict(x, predsBackgMsk)))  # logistic predictions

occVals <- raster::extract(e@predictions, modParams$occ.pts)  # get predicted values for occ grid cells
mtps <- apply(occVals, MARGIN = 2, min)  # apply minimum training presence threshold over all models
# Define 10% training presence threshold
if (length(occVals) < 10) {  # if less than 10 occ values, find 90% of total and round down
  n90 <- floor(length(occVals) * 0.9)
} else {  # if greater than or equal to 10 occ values, round up
  n90 <- ceiling(length(occVals) * 0.9)
}
p10s <- apply(occVals, MARGIN = 2, function(x) rev(sort(x))[n90])  # apply 10% training presence threshold over all models
```

### Visualize Niche Model

You chose to view visualizations of your modeling analysis results.

```{r}
dismo::response(evalMods[[2]], var = "bio7")
```

![](userReport2_files/figure-markdown_github/respCurv-1.png)

```{r}
ENMeval::eval.plot(evalTbl, value = "Mean.AUC")
```

![](userReport2_files/figure-markdown_github/evalPlot-1.png)

### Project Niche Model

You selected to project your model. First define a polygon with the coordinates you chose, then crop and mask your predictor rasters. Finally, predict suitability values for these new raster cells based on the model you selected.

```{r}
projCoords <- data.frame(x = c(-135.9821, -53.3649, -49.4977, -127.0172), y = c(61.4583, 61.1205, 8.9689, 6.8798))
projPoly <- sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(projCoords)), ID=1)))

# Select your model from the evalMods list
modSel <- evalMods[[2]]
```

### Project Niche Model to New Extent

Now use crop and mask the predictor variables by projPoly, and use the predict() function to predict the values for the new extent based on the model selected.

```{r}
predsProj <- raster::crop(preds, projPoly)
predsMsk <- raster::mask(predsProj, projPoly)

newExtProj <- dismo::predict(modSel, predsMsk)
plot(newExtProj)
```

![](userReport2_files/figure-markdown_github/projArea-1.png)

### Project Niche Model to New Time

Now download the future climate variables chosen with *Wallace*, crop and mask them by projPoly, and use the predict() function to predict the values for the new time based on the model selected.

```{r}
predsFuture <- raster::getData("CMIP5", var = "bio", res = 10, rcp = 85, model = "MR", year = 70)

predsProj <- raster::crop(predsFuture, projPoly)
predsMsk <- raster::mask(predsProj, projPoly)

# rename future climate variable names
names(predsMsk) <- names(preds)
futureProj <- dismo::predict(modSel, predsMsk)
plot(futureProj)
```

![](userReport2_files/figure-markdown_github/projTime-1.png)
