% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/derive.R
\name{derive_first_occurrence}
\alias{derive_first_occurrence}
\title{Derive a binary disease flag from UKB First Occurrence fields}
\usage{
derive_first_occurrence(data, name, field, col = NULL)
}
\arguments{
\item{data}{(data.frame or data.table) UKB phenotype data.}

\item{name}{(character) Output column prefix, e.g. \code{"disease"} produces
\code{disease_fo} and \code{disease_fo_date}.}

\item{field}{(integer or character) UKB field ID of the First Occurrence
field, e.g. \code{131666} for E11 (type 2 diabetes).}

\item{col}{(character or NULL) Name of the source column in \code{data}.
When \code{NULL} (default) the column is detected automatically from
\code{field}.}
}
\value{
The input \code{data} (invisibly) with two new columns added
in-place: \code{{name}_fo} (logical) and \code{{name}_fo_date} (IDate).
}
\description{
UKB pre-computes the earliest recorded date for hundreds of ICD-10 chapters
and categories as \emph{First Occurrence} fields (\code{p131xxx}).  Each
field contains a single date per participant; no array or instance depth is
involved.  This function reads that date, converts it to \code{IDate},
and writes two analysis-ready columns:
}
\details{
\describe{
\item{\code{{name}_fo_date}}{Earliest First Occurrence date (\code{IDate}).
Values that cannot be coerced to a valid date (e.g. UKB error codes)
are silently set to \code{NA}.}
\item{\code{{name}_fo}}{Logical flag derived from
\code{{name}_fo_date}: \code{TRUE} if and only if a valid date exists.
This guarantees that every positive case has a usable date - essential
for time-to-event and prevalent/incident classification.}
}

\strong{Column detection}: the function locates the source column
automatically from \code{field}, handling both the raw format used by
\code{\link{extract_pheno}} (\code{participant.p131666}) and the
snake_case format produced by \code{\link{decode_names}}
(\code{date_e11_first_reported_type_2_diabetes}).  Supply \code{col}
to override auto-detection.

\strong{data.table pass-by-reference}: when the input is a
\code{data.table}, new columns are added in-place via \code{:=}.
The returned object and the original variable point to the same memory.
}
\examples{
dt <- ops_toy(n = 100)
derive_first_occurrence(dt, name = "outcome", field = 131742L, col = "p131742")
}
