```{r echo=FALSE}
library(knitr)
```

\pagenumbering{gobble}

The file `crabbieMCDS.csv` has data on crabeater seals, as if you had entered these data yourself into a spreadsheet.

This short exercise guides you through the import of those data into R, and fits a simple half-normal detection function examining the possible improvement of the model by incorporating a _side of plane_ covariate.

```{r}
library(Distance)
cr.covariate <- read.csv("crabbieMCDS.csv")
head(cr.covariate)
```

Noting that the data have been read into R appropriately, we are ready to fit a detection function.

Because we are using `ddf()` to perform model fitting, it expects to have double observer data.  We are treating these data as if they were not employing the double observer configuration.  Hence a function `checkdata()` comes to our aide to configure our data into the appropriate format for `ddf()`.

Note that _side of plane_ is assigned characters (L/R) in our data.  Before using _side of plane_ as a covariate, we need to tell R that _side of plane_ takes on discrete values, hence characters are acceptable for use; this happens with the `factor()` function.

```{r}
cr.covariate.fixed <- Distance:::checkdata(cr.covariate)
cr.covariate.fixed$side <- factor(cr.covariate.fixed$side)
cr.cov.ddf <- ddf(method="ds", dsmodel=~mcds(key="hn", formula=~side),
                  data=cr.covariate.fixed$data, meta.data=list(width=700))
```

```{r}
summary(cr.cov.ddf)
```

Having fitted a detection function using _side of plane_ as a covariate to the half-normal detection function, we would like to assess the fit of this function to our data.  Two visual assessments are provided by the panels below: histogram and function on the left and QQ plot on the right.

```{r, fig.show='asis', fig.cap="Histogram and fitted half-normal detection function on left.  Q-Q plot of detection function and data on right.", fig.width=8, fig.height=5}
par(mfrow = c(1, 2))
plot.title <- "Note: two sets of points for 'side' of plane"
plot(cr.cov.ddf , lwd = 2, lty = 1, pch = 1, cex = 1, nc = 10, main = plot.title)
ddf.gof.results <- ddf.gof(cr.cov.ddf, lwd = 2, lty = 1, pch = ".", cex = 0.5, col = c(1,2))
```


We could also fit a detection function without the covariate and contrast the two models.

```{r}
cr.nocovar <- ddf(method="ds",dsmodel=~mcds(key="hn", formula=~1),
                  data=cr.covariate.fixed$data, meta.data=list(width=700))
```

```{r}
summary(cr.nocovar)
```

AIC score for model without covariate is `r options(scipen=9)` `r round(summary(cr.nocovar)$aic)` and AIC score for model with _side_ as a covariate is  `r round(summary(cr.cov.ddf)$aic)` so the model that includes _side_ as a covariate is preferred.

We could go on to produce abundance estimates from our preferred model using `dht(cr.cov.ddf)` but leave that as an exercise for the reader.

