These helpers provide a means of standardizing common indexing methods such as integer, character or logical indexing.

• vec_as_index() accepts integer, character, or logical vectors of any size. The output is always an integer vector that is suitable for subsetting with [ or vec_slice(). It might be a different size than the input because negative selections are transformed to positive ones and logical vectors are transformed to a vector of indices for the TRUE positions.

• vec_as_position() accepts a single number or string. It returns a single position as a integer vector of size 1. This is suitable for extracting with [[.

vec_as_index(
i,
n,
names = NULL,
...,
allow_types = c("indicator", "position", "name"),
convert_values = "negative",
arg = "i"
)

vec_as_position(i, n, names = NULL, ..., allow_values = NULL, arg = "i")

## Arguments

i An integer, character or logical vector specifying the positions or names of the observations to get/set. Specify TRUE to index all elements (as in x[]), or NULL, FALSE or integer() to index none (as in x[NULL]). A single integer representing the total size of the object that i is meant to index into. If i is a character vector, names should be a character vector that i will be matched against to construct the index. Otherwise, not used. The default value of NULL will result in an error if i is a character vector. Experimental. Character vector indicating one or several types of position to be allowed as input: "indicator", "position", or "name". Indicators must be subtypes of logical. Locations must be coercible to integers (possibly from a larger type like double). Names must be subtypes of character. Experimental. Character vector indicating what types of values should be converted. Can currently only be set to "negative". The argument name to be displayed in error messages when vec_as_index() and vec_as_position() are used to check the type of a function input. Experimental. Character vector indicating zero, one or several types of values to be allowed as input: "negative" or "missing". By default, positions can't be negative or missing.

## Value

vec_as_index() returns an integer vector that can be used as an index in a subsetting operation. vec_as_position() returns an integer of size 1 that can be used a scalar index for extracting an element.

## Examples

x <- array(1:6, c(2, 3))
dimnames(x) <- list(c("r1", "r2"), c("c1", "c2", "c3"))

# The most common use case validates row indices
vec_as_index(1, vec_size(x))#> [1] 1
# Negative indices can be used to index from the back
vec_as_index(-1, vec_size(x))#> [1] 2
# Character vectors can be used if names are provided
vec_as_index("r2", vec_size(x), rownames(x))#> [1] 2
# You can also construct an index for dimensions other than the first
vec_as_index(c("c2", "c1"), ncol(x), colnames(x))#> [1] 2 1