% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/arg_index.R
\name{arg_index}
\alias{arg_index}
\alias{arg_indices}
\title{Check Index Argument}
\usage{
arg_index(
  x,
  data,
  .arg = rlang::caller_arg(x),
  .arg_data = rlang::caller_arg(data),
  .msg = NULL,
  .call
)

arg_indices(
  x,
  data,
  .arg = rlang::caller_arg(x),
  .arg_data = rlang::caller_arg(data),
  .msg = NULL,
  .call
)
}
\arguments{
\item{x}{the argument to be checked}

\item{data}{a data set (i.e., a matrix or data frame)}

\item{.arg}{the name of the argument supplied to \code{x} to appear in error messages. The default is to extract the argument's name using \code{\link[rlang:caller_arg]{rlang::caller_arg()}}. Ignored if \code{.msg} is supplied.}

\item{.arg_data}{the name of the argument supplied to \code{data} to appear in error messages. The default is to extract the argument's name using \code{\link[rlang:caller_arg]{rlang::caller_arg()}}. Ignored if \code{.msg} is supplied.}

\item{.msg}{an optional alternative message to display if an error is thrown instead of the default message.}

\item{.call}{the execution environment of a currently running function, e.g. \code{.call = rlang::current_env()}. The corresponding function call is retrieved and mentioned in error messages as the source of the error. Passed to \code{\link[=err]{err()}}. Set to \code{NULL} to omit call information. The default is to search along the call stack for the first user-facing function in another package, if any.}
}
\value{
Returns \code{NULL} invisibly if an error is not thrown.
}
\description{
Checks whether an argument is a valid column index (\code{arg_index()}) of a data set or a vector thereof (\code{arg_indices()}).
}
\details{
For \code{arg_indices()}, an error will be thrown unless one of the following are true:
\itemize{
\item \code{x} is a vector of counts (see \code{\link[=arg_counts]{arg_counts()}}) less than or equal to \code{ncol(data)}
\item \code{x} is a character vector with values a subset of \code{colnames(data)}
}

For \code{arg_index()}, \code{x} additionally must have length equal to 1. Passing \code{arg_index()} ensures that \code{data[, x]} (if \code{data} is a matrix) or \code{data[[x]]} (if \code{x} is a data frame) evaluate correctly.

If \code{data} has no column names, an error will be thrown if \code{x} is a character vector.
}
\examples{
dat <- data.frame(col1 = 1:5,
                  col2 = 6:10)

f <- function(z) {
  arg_index(z, dat)
}

try(f(1))         # No error
try(f(3))         # Error: not a valid index
try(f("col1"))    # No error
try(f("bad_col")) # Error: not a valid index
try(f(1:2))       # Error: arg_index() requires scalar

mat <- matrix(1:9, ncol = 3)

g <- function(z) {
  arg_indices(z, mat)
}

try(g(1))     # No error
try(g(1:3))   # No error
try(g("col")) # Error: `mat` has no names
}
\seealso{
\code{\link[=arg_counts]{arg_counts()}}, \code{\link[=arg_character]{arg_character()}}
}
