% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/detectionHistory.R
\name{detectionHistory}
\alias{detectionHistory}
\title{Species detection histories for occupancy analyses}
\usage{
detectionHistory(
  recordTable,
  species,
  camOp,
  output = c("binary", "count"),
  stationCol = "Station",
  speciesCol = "Species",
  recordDateTimeCol = "DateTimeOriginal",
  recordDateTimeFormat = "ymd HMS",
  occasionLength,
  minActiveDaysPerOccasion,
  maxNumberDays,
  day1 = "survey",
  buffer,
  includeEffort = TRUE,
  scaleEffort = FALSE,
  occasionStartTime = "deprecated",
  datesAsOccasionNames = FALSE,
  timeZone,
  writecsv = FALSE,
  outDir,
  unmarkedMultFrameInput
)
}
\arguments{
\item{recordTable}{data.frame. the record table created by
\code{\link{recordTable}}}

\item{species}{character. species name(s) for which to compute detection histories. Can 
be either a single species name (for use with \pkg{unmarked}/\pkg{ubms}) or a vector 
of multiple species names (for input to \code{\link{communityModel}})}

\item{camOp}{The camera operation matrix as created by
\code{\link{cameraOperation}}}

\item{output}{character. Return binary detections ("binary") or counts of
detections ("count")}

\item{stationCol}{character. name of the column specifying Station ID in
\code{recordTable}}

\item{speciesCol}{character. name of the column specifying species in
\code{recordTable}}

\item{recordDateTimeCol}{character. name of the column specifying date and
time in \code{recordTable}}

\item{recordDateTimeFormat}{character. Format of column
\code{recordDateTimeCol} in \code{recordTable}}

\item{occasionLength}{integer. occasion length in days}

\item{minActiveDaysPerOccasion}{integer. minimum number of active trap days
for occasions to be included (optional)}

\item{maxNumberDays}{integer. maximum number of trap days per station
(optional)}

\item{day1}{character. When should occasions begin: station setup date
("station"), first day of survey ("survey"), a specific date (e.g.
"2015-12-31")?}

\item{buffer}{integer. Makes the first occasion begin a number of days after
station setup. (optional)}

\item{includeEffort}{logical. Compute trapping effort (number of active
camera trap days per station and occasion)?}

\item{scaleEffort}{logical. scale and center effort matrix to mean = 0 and
sd = 1?}

\item{occasionStartTime}{(DEPRECATED) integer. time of day (the full hour)
at which to begin occasions. Please use argument \code{occasionStartTime} in
\code{\link{cameraOperation}} instead.}

\item{datesAsOccasionNames}{If \code{day1 = "survey"}, occasion names in the
detection history will be composed of first and last day of that occasion.}

\item{timeZone}{character. Must be a value returned by
\code{\link[base:timezones]{OlsonNames}}}

\item{writecsv}{logical. Should the detection history be saved as a .csv?}

\item{outDir}{character. Directory into which detection history .csv file is
saved}

\item{unmarkedMultFrameInput}{logical. Return input for multi-season
occupancy models in unmarked (argument "y" in
\code{\link[unmarked]{unmarkedMultFrame}}?}
}
\value{
If a single species is provided (typical for \pkg{unmarked}/\pkg{ubms} analyses), 
returns a list with either 1, 2 or 3 elements depending on the value of \code{includeEffort} 
and \code{scaleEffort}:
\item{detection_history}{A species detection matrix}
\item{effort}{A matrix giving the number of active camera trap days per station and 
occasion (= camera trapping effort). Only returned if \code{includeEffort = TRUE}}
\item{effort_scaling_parameters}{Scaling parameters of the effort matrix. Only 
returned if \code{includeEffort} and \code{scaleEffort} are \code{TRUE}}

If multiple species are provided (for use with \code{\link{communityModel}}), returns 
a similar list structure but with \code{detection_history} containing a named list of 
detection matrices, one for each species. The effort matrix is identical for all 
species and thus returned only once.
}
\description{
This function generates species detection histories that can be used in
single-species occupancy analyses with packages \link[unmarked:unmarked-package]{unmarked} 
and \pkg{ubms}, as well as multi-species/community occupancy models via 
\code{\link{communityModel}}. It generates detection histories in different formats, 
with adjustable occasion length and occasion start time.
}
\details{
The function creates species detection matrices in two possible formats:
detection-by-date or detection-by-occasion. The start of detection histories 
is controlled by \code{day1}:
\itemize{
  \item \code{"station"}: Each station's history begins on its setup day
  \item \code{"survey"}: All stations begin on the first day of the survey
  \item A specific date (e.g., \code{"2015-12-31"}): All stations begin on this date
}
Dates must be in "YYYY-MM-DD" format if specified directly.


Two output formats are available via the \code{output} parameter:
\itemize{
  \item \code{"binary"}: Records detection (1) or non-detection (0)
  \item \code{"count"}: Records the number of detections per occasion
}


The \code{includeEffort} parameter determines how camera operation affects the output:
\itemize{
  \item If \code{FALSE}: Periods when cameras were not operational or only 
  partly operational appear as NA in the detection history. This may lose 
  species record from incomplete occasions.
  \item If \code{TRUE}: Incomplete occasions are retained. Outputs contain a 
  separate effort matrix that can be used as an observation covariate in occupancy models.
}
It is generally advisable to include effort as a covariate to account for 
uneven sampling effort.


\code{occasionLength} controls how many days are aggregated into each sampling occasion.
Note that \code{occasionStartTime} has moved to \code{\link{cameraOperation}} to ensure
proper calculation of daily effort.

The values of \code{stationCol} in \code{recordTable} must be matched by the
row names of \code{camOp} (case-insensitive), otherwise an error is raised.

For date/time formatting, \code{recordDateTimeFormat} accepts two syntax styles:
\itemize{
  \item Base R style (using \%): e.g., "\%Y-\%m-\%d \%H:\%M:\%S"
  \item lubridate style: e.g., "ymd HMS"
}
\pkg{lubridate} will be used if there are no "\%" characters in
\code{recordDateTimeFormat}. The default and recommended format is 
"YYYY-MM-DD HH:MM:SS" (e.g., "2014-09-30 22:59:59").


For multi-season studies where \code{sessionCol} was used in \code{\link{cameraOperation}},
the function automatically detects this structure. Set \code{unmarkedMultFrameInput = TRUE}
to format output for \code{unmarkedMultFrame}, with rows representing sites and columns
ordered by season-major, occasion-minor (e.g., season1-occasion1, season1-occasion2, etc.).
}
\section{Warning}{
 Setting \code{output = "count"} returns a count of
detections, not individuals. These counts are not suitable for abundance modeling
(e.g., N-mixture models) as they do not represent individual animals.

For important information about the \code{timeZone} parameter, please refer to
the "Data Extraction" vignette (\code{vignette("DataExtraction")} or online at
\url{https://cran.r-project.org/package=camtrapR/vignettes/camtrapr3.pdf}).
}

\examples{


# define image directory
wd_images_ID <- system.file("pictures/sample_images_species_dir", package = "camtrapR")

# load station information
data(camtraps)

# create camera operation matrix
camop_no_problem <- cameraOperation(CTtable      = camtraps,
                                    stationCol   = "Station",
                                    setupCol     = "Setup_date",
                                    retrievalCol = "Retrieval_date",
                                    hasProblems  = FALSE,
                                    dateFormat   = "dmy"
)

\dontrun{
if (Sys.which("exiftool") != ""){        # only run this function if ExifTool is available
recordTableSample <- recordTable(inDir               = wd_images_ID,
                                 IDfrom              = "directory",
                                 minDeltaTime        = 60,
                                 deltaTimeComparedTo = "lastRecord",
                                 exclude             = "UNID",
                                 timeZone            = "Asia/Kuala_Lumpur"
)
}
}
data(recordTableSample)    # load the record history, as created above


# compute detection history for a species

# without trapping effort
DetHist1 <- detectionHistory(recordTable         = recordTableSample,
                            camOp                = camop_no_problem,
                            stationCol           = "Station",
                            speciesCol           = "Species",
                            recordDateTimeCol    = "DateTimeOriginal",
                            species              = "VTA",
                            occasionLength       = 7,
                            day1                 = "station",
                            datesAsOccasionNames = FALSE,
                            includeEffort        = FALSE,
                            timeZone             = "Asia/Kuala_Lumpur"
)

DetHist1                     # this is a list with 1 element
DetHist1$detection_history   # this is the contained detection/non-detection matrix


# with effort / using base R to define recordDateTimeFormat
DetHist2 <- detectionHistory(recordTable          = recordTableSample,
                             camOp                = camop_no_problem,
                             stationCol           = "Station",
                             speciesCol           = "Species",
                             recordDateTimeCol    = "DateTimeOriginal",
                             species              = "VTA",
                             occasionLength       = 7,
                             day1                 = "station",
                             datesAsOccasionNames = FALSE,
                             includeEffort        = TRUE,
                             scaleEffort          = FALSE,
                             timeZone             = "Asia/Kuala_Lumpur"
)

DetHist2$detection_history  # detection history  (alternatively, use: DetHist2[[1]])
DetHist2$effort             # effort (alternatively, use: DetHist2[[2]])

# with effort / using lubridate package to define recordDateTimeFormat
DetHist2_lub <- detectionHistory(recordTable          = recordTableSample,
                                 camOp                = camop_no_problem,
                                 stationCol           = "Station",
                                 speciesCol           = "Species",
                                 recordDateTimeCol    = "DateTimeOriginal",
                                 recordDateTimeFormat = "ymd HMS",
                                 species              = "VTA",
                                 occasionLength       = 7,
                                 day1                 = "station",
                                 datesAsOccasionNames = FALSE,
                                 includeEffort        = TRUE,
                                 scaleEffort          = FALSE,
                                 timeZone             = "Asia/Kuala_Lumpur"
)    

DetHist2_lub$detection_history  # detection history  (alternatively, use: DetHist2_lub[[1]])
DetHist2_lub$effort             # effort (alternatively, use: DetHist2_lub[[2]])


# multi-season detection history

# load multi-season data
data(camtrapsMultiSeason)
data(recordTableSampleMultiSeason)

# multi-season camera operation matrix
camop_season <- cameraOperation(CTtable          = camtrapsMultiSeason,
                                    stationCol   = "Station",
                                    setupCol     = "Setup_date",
                                    sessionCol   = "session",
                                    retrievalCol = "Retrieval_date",
                                    hasProblems  = TRUE,
                                    dateFormat   = "dmy"
)

# multi-season detection history
DetHist_multi_season <- detectionHistory(recordTable      = recordTableSampleMultiSeason,
                            camOp                  = camop_season,
                            stationCol             = "Station",
                            speciesCol             = "Species",
                            species                = "VTA",
                            occasionLength         = 10,
                            day1                   = "station",
                            recordDateTimeCol      = "DateTimeOriginal",
                            includeEffort          = TRUE,
                            scaleEffort            = FALSE,
                            timeZone               = "UTC",
                            unmarkedMultFrameInput = TRUE
)

DetHist_multi_season


# Multi-species example for community occupancy analysis with communityModel()
DetHist_multi_species <- detectionHistory(recordTable = recordTableSample,
                                 species = c("VTA", "PBE", "EGY"),   # multiple species
                                 camOp = camop_no_problem,
                                 stationCol = "Station",
                                 speciesCol = "Species",
                                 recordDateTimeCol = "DateTimeOriginal",
                                 occasionLength = 7,
                                 day1 = "station",
                                 includeEffort = TRUE,
                                 scaleEffort = FALSE,
                                 timeZone = "Asia/Kuala_Lumpur"
)


# bundle input data for communityModel
data_list <- list(ylist = DetHist_multi_species$detection_history,
                  siteCovs = camtraps,
                  obsCovs = list(effort = DetHist_multi_species$effort))


\dontrun{

# create community model
mod.jags <- communityModel(data_list,
                           ...) # model specification 
}

}
\author{
Juergen Niedballa
}
