% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/derive.R
\name{derive_covariate}
\alias{derive_covariate}
\title{Prepare UKB covariates for analysis}
\usage{
derive_covariate(
  data,
  as_numeric = NULL,
  as_factor = NULL,
  factor_levels = NULL,
  max_levels = 5L
)
}
\arguments{
\item{data}{(data.frame or data.table) UKB data, typically output of
\code{\link{derive_missing}}.}

\item{as_numeric}{(character or NULL) Column names to convert to
\code{numeric}. Values that cannot be coerced (e.g. residual text) become
\code{NA} with a warning. Default: \code{NULL}.}

\item{as_factor}{(character or NULL) Column names to convert to
\code{factor}. Default levels are the sorted unique non-NA values unless
overridden by \code{factor_levels}. Default: \code{NULL}.}

\item{factor_levels}{(named list or NULL) Custom level ordering for specific
factor columns. Names must match entries in \code{as_factor}; values are
character vectors of levels in the desired order (first level = reference
group in regression). Columns not listed use default ordering.
Default: \code{NULL}.}

\item{max_levels}{(integer) Factor columns with more levels than this
threshold trigger a warning suggesting the user consider collapsing
categories. Default: \code{5L}.}
}
\value{
The input \code{data} with converted columns. Always returns a
\code{data.table}.
}
\description{
Converts decoded UKB columns to analysis-ready types: character-encoded
numeric fields to \code{numeric}, and categorical fields to \code{factor}.
Prints a concise summary for each converted column - mean / median / SD /
missing rate for numeric columns, and level counts for factor columns - so
you can verify distributions without leaving the pipeline.
}
\details{
\strong{data.table pass-by-reference}: when the input is a
\code{data.table}, modifications are made in-place. Pass
\code{data.table::copy(data)} to preserve the original.
}
\examples{
dt <- ops_toy(n = 100)
dt <- derive_missing(dt)
# messy_label is a character column with numeric-looking values ("-1", "999")
# mixed with non-parseable strings — demonstrates coercion and NA warnings
derive_covariate(dt,
  as_numeric = "messy_label",
  as_factor  = c("p31", "p20116_i0"),
  factor_levels = list(
    p20116_i0 = c("Never", "Previous", "Current")
  )
)
}
